Intervals and Timeouts

A brief look at delaying the execution of functions.

Scroll down...




This is a very brief lesson but covers some important concepts -- intervals and timeouts. Both of these, which you've seen before briefly, allow you to delay the execution of JavaScript functions for a set period of time. You can probably imagine that you need to be very mindful of your execution context (this) when something has been delayed.

Timing with setTimeout and setInterval

There are two plain-JavaScript functions that are very important when you're thinking about event queues and delays. You've already (briefly) seen setTimeout. It's more continuous cousin is setInterval.

Both these functions are top-level methods of the browser's Window object (so the window. is implicit). Both of them use JavaScript to hook into your browser's timing API. They give you the power to step through time in a controlled fashion.

setTimeout allows you to delay execution of a specified function for a specified amount of time (in milliseconds).

setInterval is used by all kinds of other functions behind the scenes, including many of jQuery's animations. It allows you to specify the interval on which a repetitive action should run (in milliseconds).

For example:

// wait a second to execute this
  console.log( "FINALLY!!!" );
}, 1000);

// do this EVERY second
  console.log( "AGAIN!!!" );
}, 1000);

You might imagine a simple digital clock animation which takes advantage of this. Or maybe an in-browser game which uses it to govern the game loop speed. Just note that, as with animations, overloading your processor with constant computationally-intensive events can make things very choppy.

Stopping Intervals and Timeouts

If you just create intervals in the global namespace like we did above, there's no way to stop them. Sorry...

When you create an interval and set it equal to a global variable (no var keyword), you can later use the clearInterval function to stop its execution. The same is true if you're waiting for a timeout, which clears with clearTimeout.

For example:

// Never gonna stop it...
setInterval(function(){console.log("Forever...")}, 1000);

// Stoppable if it's been set to a GLOBAL variable
myInterval = setInterval(function(){...}, 1000);

// Same is true for timeouts, which will
// never execute if cleared before they've run
myTimeout = setTimeout(function(){...}, 10000);
clearTimeout(myTimeout); remember to save your intervals and timeouts to variables if you want to be able to control them!

How Intervals and Timeouts Work

We won't go into depth, but it's useful to have a mental model for how these things work. You'll get some more glimpses of this down the line.

Basically, your browser is just a big looping function (as we've seen before) that runs many times per second. One of the APIs that you can interface with using the actual web browser is a timing API, which allows you to register functions to be called at a specific time.

As part of your browser's continuous thread, it will check with all the functions that have been registered to see if it's time to execute them yet. If so, it sends their callbacks to the normal position in the execution queue. If not, it ignores it until the next loop.

The takeaway here is that setInterval and setTimeout aren't magic, they simply interface with your browser's timing API to register their callbacks to execute at the appropriate times.

You can read Mozilla's WindowTimers docs if you want to see the available methods.

Code Review

The important bits of code from this lesson

// delay execution with a timeout

// set a never-ending interval
setInterval(function(){console.log("Forever...")}, 1000);

// Stop a globally named interval
myInterval = setInterval(function(){...}, 1000);

// Stop a globally named timeout before it runs
myTimeout = setTimeout(function(){...}, 10000);

Wrapping Up

Intervals and Timeouts are simple concepts in isolation but, to use them effectively, you need to have a comfortable understanding of how JavaScript hangs onto variables and determines this. You'll get more exposure to this in upcoming sections which dig deeper into how variables are kept in scope using closures.

Sign up to track your progress for free

There are ( ) additional resources for this lesson. Check them out!

Sorry, comments aren't active just yet!

Next Lesson: JS Best Practices