Chapter 6

Scheduling the Execution of Functions Using Timers

WHAT’S IN THIS CHAPTER?

  • Deferring the execution of a function
  • Canceling a scheduled execution
  • Scheduling a periodic execution of a function
  • Deferring the execution of a function until the next event loop tick

If you are accustomed to programming in browser JavaScript, you probably use the setTimeout and setInterval functions. These functions allow for the deferred execution of a function after a given period of time. For example, the following snippet of code, once loaded into a web page, appends the string "Hello there" after one second has elapsed:

var oneSecond = 1000 * 1; // one second = 1000 x 1 ms
setTimeout(function() {
    document.write('<p>Hello there.</p>');
}, oneSecond);

setInterval allows for the repetitive execution of a function spaced by a given time interval. If you inject the following snippet into a web page, it will also append the phrase "Hello there" to the document and keep doing so every second:

var oneSecond = 1000 * 1; // one second = 1000 x 1 ms
setInterval(function() {
    document.write('<p>Hello there.</p>');
}, oneSecond);

The need for these functions has arisen because the web has become a platform for building applications instead of static web pages. These scheduling functions help developers build periodic form validation, deferred remote data syncing, and all sorts of user interface interactions that require a delayed reaction. Node implements this exact set of functions. On the server side ...

Get Professional Node.js: Building Javascript Based Scalable Software now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.