Mastering Node.js(Second Edition)
上QQ阅读APP看书,第一时间看更新

 setInterval

One can think of many cases where being able to periodically execute a function would be useful. Polling a data source every few seconds and pushing updates is a common pattern. Running the next step in an animation every few milliseconds is another use case, as is collecting garbage. For these cases, setInterval is a good tool:

let intervalId = setInterval(() => { ... }, 100);

Every 100 milliseconds the sent callback function will execute, a process that can be cancelled with clearInterval(intervalReference).

Unfortunately, as with setTimeout, this behavior is not always reliable. Importantly, if a system delay (such as some badly written blocking while loop) occupies the event loop for some period of time, intervals set prior and completing within that interim will have their results queued on the stack. When the event loop becomes unblocked and unwinds, all the interval callbacks will be fired in sequence, essentially immediately, losing any sort of timing delays they intended.

Luckily, unlike browser-based JavaScript, intervals are rather more reliable in Node, generally able to maintain expected periodicity in normal use scenarios.