Sunday, June 29, 2014

Handle process in [Node.js]

Use of process handle:

 Some time When you write program , before end of your program you want to clear some connection , thread, memory . In such case while terminate your process you need to write some code.

In Node.js The process object is a global object and can be accessed from anywhere. 

Who will handle method in process.

 Node.js runtime process will call handlers assign in process objects.


How to use.

 process.on('exit', function(code) {  
  console.log("On Exit Start");  
  setTimeout(function() {  
   console.log('This will not run');  
  }, 1000);  
  console.log('About to exit with code:', code);  
 });  
 console.log("Current Time-"+new Date());    
  var timerId=setTimeout(function(){   
  console.log("Current Time-"+new Date());    
  }, 5000);   




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