- Mastering Node.js(Second Edition)
- Sandro Pasquali Kevin Faaborg
- 238字
- 2021-07-02 19:28:44
setTimeout
Timeouts can be used to defer the execution of a function until some number of milliseconds into the future.
Consider the following code:
setTimeout(a, 1000);
setTimeout(b, 1001);
One would expect that function b would execute after function a. However, this cannot be guaranteed — a may follow b, or the other way around.
Now, consider the subtle difference present in the following code snippet:
setTimeout(a, 1000);
setTimeout(b, 1000);
The execution order of a and b are predictable in this case. Node essentially maintains an object map grouping callbacks with identical timeout lengths. Isaac Schlueter, a former leader of the Node project and now CEO of npm Inc., puts it in this way: