Skip to content

Instantly share code, notes, and snippets.

@adamsilverstein
Last active January 9, 2024 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamsilverstein/665b0738bb335f21142fe1e969a7f7df to your computer and use it in GitHub Desktop.
Save adamsilverstein/665b0738bb335f21142fe1e969a7f7df to your computer and use it in GitHub Desktop.
Yield to main thread
/*
* Yielding method using scheduler.yield, falling back to setTimeout:
*/
async function yieldToMain() {
if('scheduler' in window && 'yield' in scheduler) {
return await scheduler.yield();
}
return new Promise(resolve => {
setTimeout(resolve, 0);
});
}
/*
* Yielding to the main thread before changing the state of the component:
*/
const observer = new IntersectionObserver((entries) => {
entries.forEach(handleIntersection);
const maxNumberOfEntries = Math.max(...this.intersectingEntries);
if (Number.isFinite(maxNumberOfEntries)) {
await this.yieldToMain();
this.setState({ count: maxNumberOfEntries });
}
}, { threshold: 0.5 });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment