Tuesday, June 10, 2014

Timeout and Interval Timers In [Node.js]

Timer is use for running asynchronous Thread in Node js program.


API For Timer 

setTimeout(callback, delay, [arg], [...])
clearTimeout(timeoutObject)
setInterval(callback, delay, [arg], [...])
clearInterval(intervalObject)


How it works - setTimeout-clearTimeout.

To schedule a function execution of a one-time callback after delay milliseconds. Returns a timeoutObject for possible use with clearTimeout(). Optionally you can also pass arguments to the callback
setTimeout
 console.log("Current Time-"+new Date());   
 setTimeout(function(){  
  console.log("Current Time-"+new Date());   
 }, 1000)  







clearTimeout
 If you started any thread or task using settimeout you can kill/stop that using clearTimeout.

 console.log("Current Time-"+new Date());   
 var timerId=setTimeout(function(){  
  console.log("Current Time-"+new Date());   
 }, 5000);  
 clearTimeout(timerId);  

 In this case 2nd Current Time won't print because we clear the timer with ID




How it works - setInterval-clearInterval.

To schedule the repeated function  execution of callback every delay milliseconds. Returns a intervalObject for possible use with clearInterval(). Optionally you can also pass arguments to the callback.

 console.log("Current Time-"+new Date());   
 setInterval(function(){  
  console.log("Current Time-"+new Date());   
 }, 1000)  



clearInterval
 If you started any thread or task using setInterval you can kill/stop that using clearInterval.

 console.log("Current Time-"+new Date());   
 var counter=0;  
 var timerId=setInterval(function(){  
  console.log("Current Time-"+new Date());   
  counter++;  
  if(counter==3)  
  {  
   console.log("clearInterval after 3");  
   clearInterval(timerId);  
  }  
 }, 1000);  

  In this case After 3 sec Interval will stop  because we clear the interval with ID


No comments:

Post a Comment