Times will come when you might want to get a piece of code in JavScript executed after a certain amount of time frame. For instance you might want to delay a subscription pop up box on your blog for about 1 minute from the time the page completely loads.

In such cases we can use the two functions setTimeout() and setInterval() to time our code.

Technically speaking, rather than saying code we should use the term function - in JavaScript we can get only functions delayed/timed before getting invoked.

Setting timers

So now shall we go on to implement these methods in real?

Both the functions setTimeout() and setInterval() take two arguments - the first one is the function to be timed, and the second one is a number indicating the amount of this time, in milliseconds.

Both of them work essentially the same way but do different tasks. Let's see each one starting with setTimeout().

setTimeout() - once

setTimeout calls its argument function only once after the specified amount of time.

setTimeout(function() {
}, 3000);

After 3000ms, or in other words 3s we get a log made in the console and that's it. As the name implies setTimeout() just sets a time out before its argument function is invoked.

Comparitive to this, setInterval() calls its argument function repeatedly after the given amount of time. The function will keep on executing after the interval, unless and until it is cleared. We'll see what clearing means shortly.

setInterval() - again and again

Following we have the same function as in the example above but this time in setInterval():

setInterval(function() {
}, 3000);

And when this code gets executed, with every passing 3s we get a log made in the console. setInterval() calls its function after the given amount of interval, again and again.

Hence as the name suggests setInterval() sets an interval after which to call the provided function.

Canceling timers

Knowing how to cancel timers is equally important to knowing how to create them. Especially for setInterval(), which keeps on calling its argument function, we need to at some point preferably cancel the interval when we don't need it.

Canceling timers can also apply to timeouts - if one is set for let's say 1 min, you can cancel it before executing it.

In short, canceling timers is in approximate equilibrium with creating timers.

JavaScript provides us with two very simple methods to cancel timeouts and intervals using the functions clearTimeout() and clearInterval() respectively. Both functions take an id returned from creating the corresponding timer. Let's see what this means...

The functions setTimeout() and setInterval() both return an ID when they are executed. This ID can then be used in clearTimeout() and clearInterval() respectively, to clear them out of the timer stack.

We can save the ID in a variable and in this way be able to utilise it later in the script.

Following we save the ID returned by setTimeout() in a variable id and use it to clear the timeout before it gets fired. Nothing gets logged in the console since the timeout is cleared before it can be executed.

var id = setTimeout(function() {
}, 3000); // returns an ID

clearTimeout(id); // clear the timeout

A similar example with setInterval():

var id = setInterval(function() {
}, 3000); // returns an ID

clearTimeout(id); // clear the interval

And again nothing gets logged in the console since the interval is cleared before it can be executed.

Now that we've essentially covered all on JavaScript timers, we can now experiment with making certain combinations of the learnt concepts in solving the problems below.

Let's see if you can relate the ideas to answer the questions below.

Clearing an interval after sometime

How can you clear an interval after 5 seconds? It is given that you have to use timers only.

Try to think for sometime what do you really need in order to accomplish this simple task. For a hint - you need a timeout.

Here's how to solve this problem:

var id = setInterval(function() {
}, 1000); // interval firing every 1s

setTimeout(function() {
    clearInterval(id); // clear the interval
}, 5000); // fire after 5s

We set a timeout of 5s after which we call a function that clears the interval set previously. Piece of cake, right?

Repeated execution using setTimeout()

How can you get a function repeatedly executed using setTimeout only after every 1 second?

This might be a fairly difficult question, for at least those who don't have a good understanding of JavaScript functions. Can you solve it?

For a hint - setTimeout() can't ever call its function again and again on its own like setInterval(). We just utilise a trick; a concept in functions; to get setTimeout() executed repeatedly.

Can you remember something from functions, relating to the idea of repeatedness?

Function Recursions are the solution for this case.

However the recursion here is a bit offset from the general pattern of recursions we have seen - a function calling itself. What we have here is instead a function making a call to itself in a timeout manner.

function logger() {
    setTimeout(logger, 1000); // calls logger after 1s

logger() // calls logger after 1s

The trick over here is the 3rd line, which actually brings about a repeated behaviour using setTimeout ONLY.

And now if you want to give a repeated timing to any of your function's invocations, you can choose from any of the two ways: setInterval() or a recursive setTimeout().

Its all your need and choice!