O'Reilly logo

Professional Node.js: Building Javascript Based Scalable Software by Pedro Teixeira

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required