Being able to control the timing of events/methods is a powerful tool for controlling animations, timing game states and reducing code bottlenecks.

In JavaScripts there are two methods we can use to control timed events
setInterval(‘function’, intervalTime) – This will fire the method repeatedly every X milliseconds.
setTimeout(‘function’, intervalTime) – This will fire the method once at X milliseconds.

below are usage examples of each

setInterval


//this will fire the doSomething method over and over every 1000milliseconds (1 second).
//pass function in as first parameter and time in milliseconds as 2nd parameter
var myInterval = setInterval(function(){
doSomething()
}, 1000);

function doSomething()
{
console.log("doSomething fired!");
}

To stop setInterval from firing we can ‘clearInterval()’ and pass in the interval var

clearInterval(myInterval)

setTimeout


//this will fire the doSomething method once at 1000 milliseconds
//pass the function in as first parameter and time in milliseconds as 2nd parameter
var myTimeout = setTimeout(function(){
doSomething()
}, 1000);

function doSomething()
{
console.log("doSomething fired once!");
}

To stop setTimeout before the first time, we call ‘clearTimeout()’ and pass in the timeout var

clearTimeout(myTimeout)