Last active
January 9, 2024 20:59
-
-
Save adamsilverstein/665b0738bb335f21142fe1e969a7f7df to your computer and use it in GitHub Desktop.
Yield to main thread
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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