Setting timers

setTimeout

The setTimeout function schedules another function to be called later. It is similar to requestAnimationFrame.

In the below example instead of calling the function at the next redraw, it waits for a given amount of milliseconds. This page turns from blue to yellow after two seconds.

<script>
document.body.style.background = "blue";
setTimeout(function() {
    document.body.style.background = "yellow";
}, 2000); &
lt;
/script>
clearTimeout

Sometimes you need to cancel a function you have scheduled. This is done by storing the value returned by setTimeout and calling clearTimeout on it.

var bombTimer = setTimeout(function() {
    console.log("BOOM!");
}, 500);
if (Math.random() & lt; 0.5) { //50%chance
    console.log("Defused.");
    clearTimeout(bombTimer);
}

The cancelAnimationFrame function works in the same way as clearTimeout —calling it on a value returned by requestAnimationFrame will cancel that frame (assuming it hasn't already been called).

A similar set of functions, setInterval and clearInterval are used to set timers that should repeat every X milliseconds.

var ticks = 0;
var clock = setInterval(function() {
    console.log("tick", ticks++);
    if (ticks == 10) {
        clearInterval(clock);
        console.log("stop.");
    }
}, 200);
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents