-
-
Save thepassle/909a86fc70794ef24a5aa3376b900844 to your computer and use it in GitHub Desktop.
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
class Batching { | |
/** | |
* We declare and initialize a variable to keep track of whether | |
* or not an update has already been requested | |
*/ | |
updateRequested = false; | |
scheduleUpdate() { | |
/** | |
* In here, we need a check to see if an update is already previously requested. | |
* If an update already is requested, we don't want to do any unnecessary work! | |
*/ | |
if(!this.updateRequested) { | |
/* If no update has yet been requested, we set the `updateRequested` flag to `true` */ | |
this.updateRequested = true; | |
/** | |
* Since we now know that microtasks run after JavaScript has finished | |
* executing, we can use this knowledge to our advantage, and only set | |
* the `updateRequested` flag back to `false` again once all the tasks | |
* have run, essentially delaying, or _batching_ the update! | |
*/ | |
Promise.resolve().then(() => { | |
this.updateRequested = false; | |
this.update(); | |
}); | |
} | |
} | |
/* This is our `update` method that we only want to be called once */ | |
update() { | |
console.log('updating!'); | |
} | |
} | |
const batching = new Batching(); | |
/* We call scheduleUpdate in quick succession */ | |
batching.scheduleUpdate(); | |
batching.scheduleUpdate(); | |
batching.scheduleUpdate(); | |
/* 🎉 The result: */ | |
// "updating!" | |
/* `update` only ran once! */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment