Thursday, 5 April 2012

Timers in Nods.js


You can use the JavaScript timers, such as setTimeout(), clearTimeout(), setInterval(), clearInterval() in your node apps. All of the timer functions are globals. You do not need to require() this module in order to use them.
To schedule the repeated execution of callback every delay milliseconds you can use the setInterval() method. The setInterval returns an intervalId which can be later used to clear the interval execution with the clearInterval() method.
Similary to schedule execution of a one-time callback after delay milliseconds use the setTimeout() method.
var index = 0;

setTimeout(function (timeoutMessage) {
    console.log(timeoutMessage);
}, 100, 'Hello timeout');

var intervalId = setInterval(function (message) {
    index++;
    if (index == 5) {
        clearInterval(intervalId);
    }
    console.log(message);
}, 200, 'Hello interval');


No comments:

Post a Comment