Home >>Nodejs Tutorial >Node.js Timer

Node.js Timer

Node.js Timer

The Timer functions for Node.js are global functions. To use timer functions you don't need to use require() function. Let's take a look at the timer function list.

Set timer functions:

SetImmediate(): Uses setImmediate to execute.

SetInterval(): Defines time intervals.

SetTimeout():()-Runs a one-time callback after millisecond delay.

Clear timer functions:

ClearImmediate(immediateObject): It is used to avoid an immediateObject generated by setImmediate

ClearInterval(intervalObject):it is used to avoid an intervalObject generated by setInterval

ClearTimeout(timeoutObject):it stops a timeoutObject created by setTimeout

Node.js Timer setInterval() Example

This example sets a time interval of 1000 milliseconds and shows the specified comment after every 1000 millisecond until you finish.

File: timer1.js


setInterval(function() 
{  
 console.log("setInterval: 1 millisecond completed!..");   
}, 1000);  

Open command prompt Node.js and execute the following code:

node timer1.js 

File: timer5.js


var i =0;  
console.log(i);  
setInterval(function(){  
i++;  
console.log(i);  
}, 1000);   

Open command prompt Node.js and execute the following code:

node timer5.js 

Node.js Timer setTimeout() Example

File: timer1.js


setTimeout(function() 
{   
console.log("setTimeout: 1000 millisecond completed!..");  
}, 1000);  

Open command prompt Node.js and execute the following code:

node timer1.js 

This example demonstrates time out without setting a time interval for every 1000 milliseconds. This example uses the a function's recursion property.

File: timer2.js


var recursive = function ()
{  
console.log("1000 millisecond completed!..");   
setTimeout(recursive,1000);  
}  
recursive();   

Open command prompt Node.js and execute the following code:

node timer2.js 

Node.js setInterval(), setTimeout() and clearTimeout()

Let's see an example for the function clearTimeout().

File: timer3.js


function welcome () 
{  
console.log("Welcome to Phptpoint!");  
}  
var id1 = setTimeout(welcome,1000);  
var id2 = setInterval(welcome,1000);  
clearTimeout(id1);  
//clearInterval(id2);  

Open command prompt Node.js and execute the following code:

node timer3.js 

You will see, in fact, that the illustration above is recursive. If you use ClearInterval it will terminate after one move.

Node.js setInterval(), setTimeout() and clearInterval()

Let's see an example for using the function clearInterval().

File: timer3.js


function welcome () 
{  
console.log("Welcome to Phptpoint!");  
}  
var id1 = setTimeout(welcome,1000);  
var id2 = setInterval(welcome,1000);  
//clearTimeout(id1);  
clearInterval(id2);  

Open command prompt Node.js and execute the following code:

node timer3.js