Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #454 from atomiks/defer
[ADD: `defer.md`] defer
- Loading branch information
Showing
2 changed files
with
20 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
### defer | ||
|
||
Defers invoking a function until the current call stack has cleared. | ||
|
||
Use `setTimeout()` with a timeout of 1ms to add a new event to the browser event queue and allow the rendering engine to complete its work. Use the spread (`...`) operator to supply the function with an arbitrary number of arguments. | ||
|
||
```js | ||
const defer = (fn, ...args) => setTimeout(fn, 1, ...args); | ||
``` | ||
|
||
```js | ||
// Example A: | ||
defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a' | ||
|
||
// Example B: | ||
document.querySelector('#someElement').innerHTML = 'Hello'; | ||
longRunningFunction(); // the browser will not update the HTML until this has finished | ||
defer(longRunningFunction); // the browser will update the HTML then run the function | ||
``` |
This file contains 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