JavaScript Time events

Time is one important aspects in interaction design, animations, sliders, tabs, event loaders, etc. are depended on timer for proper functioning. JavaScript provides two amazing timing event api’s

the first one is : SetTimeout();

//following is the code for calling this little sweet function  

window.setTimeout(function, milliseconds); 




//it takes a function and millisecond as the second parameters 
//For Example: 

window.setTimeout(hi,2000); 

function hi(){
console.log("i am evoked after 2000 milli seconds"); 
}

Pretty easy right? Here’s the second one!

window.setInterval();
now this second one, is a bit diffrent from previous one, it acts like a ticker or heartbeat, it contentiously evokes the function which is passed.

//Sample code for setInterval() method

setInterval(hi, 1000);
// hi is the function, and 1000 (second parameter) is the time or heartbeat time. 
// it would evoke hi function in every 1000 millisecond or 1 second 

function hi() {

  console.log("beat..."); 
}

the problem with above code is that, once you initiate it’s impossible to stop, however if you assign a var, then you would be able to remove / clear the interval or timeout.

//for example

var time = setInterval(function name,  milliseconds);
clearInterval(time); 

// and for timeout 

var time = setTimeout(function name, milliseconds);
clearTimeout(time);

 

About the author

sarabpreet

Add comment

By sarabpreet

Latest from Sarabpreet