Using Timeouts and Intervals

Using Timeouts and Intervals
bluehost placeholder image

Timeouts and intervals allow you to control when and how often a function is invoked. The two are similar in usage but their functionalities are different, and we'll learn that difference, along with how to cancel, or clear, them when we are done with them.

Set Timeout

A timeout lets you run a function after a certain amount of time has elapsed. This is done with the setTimeout function that takes as its parameters the function to run and in how much time into the future (in milliseconds).

For example, you can set a timeout to make a function execute five seconds into the future:

	
    function sayHello() {
        console.log("Hello!");
    }

    var timeout = setTimeout(sayHello, 5 * 1000);
	
	
    Hello!
	
  • JS
Run

If you run the code, you will notice that the logging will not happen until five seconds pass. That's the power of timeouts, being able to run code in the future.

Clear Timeout

So what if we change our mind about running that function in the future? We can clear it using the clearTimeout function.

Let's say we set it to print but immediately change our minds:

	
    function sayHello() {
        console.log("Hello!");
    }

    var timeout = setTimeout(sayHello, 5 * 1000);

    clearTimeout(timeout);
	

Because we used clearTimeout on our timeout, it was cleared and no longer active. It will basically act as if it never existed and therefore nothing will get printed on the screen.

siteground placeholder image

Set Interval

Intervals are a simpler way of making the same code repeat over and over again, with a set amount of time in between, the interval time. You can think of intervals as basically timeouts that call themselves at the end to start the cycle all over again.

Let's create an interval using setInterval to build a basic timer:

	
    var seconds = 0;

    function printTime() {
        seconds++;
        console.log("Seconds elapsed: " + seconds);
    }

    var interval = setInterval(printTime, 1000);
	
	
    Seconds elapsed: 1
    Seconds elapsed: 2
    Seconds elapsed: 3
    Seconds elapsed: 4
    Seconds elapsed: 5
	
  • JS
Run

We are calling printTime once every second and inside that function we are both incrementing the seconds variable and printing it out. As this continues on, it serves as a basic way to keep track of how much time has passed since the page has loaded.

Clear Interval

As with clearTimeout, clearInterval is a way you can clear your intervals and prevent it from continuing on forever. Sticking with our timer example, let's say you wanted to stop repeating once you hit 10 seconds.

	
    var seconds = 0;

    function printTimeUntil10() {
        seconds++; // increment seconds by 1
        console.log("Seconds elapsed: " + seconds);

        if (seconds === 10) {
            console.log("10 seconds has elapsed!")
            clearInterval(interval); // we're done, clear it!
        }
    }

    var interval = setInterval(printTimeUntil10, 1000);
	
	
    Seconds elapsed: 1
    Seconds elapsed: 2
    Seconds elapsed: 3
    Seconds elapsed: 4
    Seconds elapsed: 5
    Seconds elapsed: 6
    Seconds elapsed: 7
    Seconds elapsed: 8
    Seconds elapsed: 9
    Seconds elapsed: 10
    10 seconds has elapsed!
	
  • JS
Run

We have a nifty condition that checks if we finally hit 10 seconds, and once we do, we clear the interval so it stops repeating and print out a nice message letting us know that we hit the desired number of seconds.