logo javascript

Javascript Course for Beginners

Instructor: Ivan Lourenço Gomes

Time methods

The window object has two methods that allow us to delay the execution of a block of code or execute it repetitively between an interval of time.

setTimeout

The setTimeout function accepts two arguments: the function that should be executed after the stipulated time and the stipulated time in milliseconds.

This function passed as an argument is a callback function, something that will be further explained later in the course.

                    
    
    window.setTimeout(callback function,time in milliseconds)

                    
                

Let's send one message to the console, wait 3 seconds, then send another.

                    

    console.log("Message 1");

    window.setTimeout(function() {
        console.log("Message 2");
    },3000);

                    
                

Another example would be showing an element for a given period of time, let's say a spinner loader.

                    

    document.getElementById("show-loader").onclick = function () {

        document.getElementById("spinner-loader").style.display = "block";
        window.setTimeout(function(){
            document.getElementById("spinner-loader").style.display = "none";
        }, 5000);

    };

                    
                

setInterval

The SetInterval method is similar to the setTimeout, the difference is that it keeps repeating the callback function forever, unless you stop it.

                    
    var count = 0;
    window.setInterval(function(){
        console.log(count);
        count++;
    }, 1000);
    
                    
                
Interrupting time methods

Both setTimeout and setInterval can be interrupted. To do this we need to assign them to a variable and then use the clearTimeout or clearInterval respectively.

Let's limit the above code to 5 seconds:

                    

    var count = 0;

    var timeInterval = window.setInterval(function(){
        console.log(count);
        count++;
        if (count > 5) {
            window.clearInterval(timeInterval);
        }
    }, 1000);
    
                    
                

The clock challenge

Use the Date object and the setInterval methods to make the clock below work in real time.

00 : 00 : 00

Contents