Open In App

Explain the working of timers in JavaScript

Last Updated : 27 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss the working of timers in JavaScript in detail.

As we know JavaScript is an asynchronous and single-threaded programming language. This means there is only one call-stack and inside that call-stack code is executed one by one.

Synchronous means code is executed one by one and single-threaded means we have only one main thread that is call-stack. But we can achieve asynchronous functionality also.

A timer is used to execute some task after a particular time interval. Basically, with the help of a timer in JavaScript, we can delay the code execution. With the help of the timer function in JavaScript, we can achieve asynchronous functionality also.

Suppose we are delaying the execution of some function with the help of timer function then that function will not get executed when the JavaScript engine will encounter it. It would be stored somewhere else and when the timer expired then that function would be executed.

JavaScript provides two functions to delay the execution of tasks. These are timer functions.

  • setTimeout function
  • setInterval function

Working of timers in JavaScript: Now let’s discuss how the timer function actually runs.

We will understand it with an example.

Example: 

Javascript




function print() {
    console.log("Welcome to GFG");
}
setTimeout(print, 5000);
console.log("Hello World!");


Output:

Hello World!
Welcome to GFG

Explanation: In this case, very interestingly first console.log(“Hello World!”) is executed and then setTimout is executed. Reason when we run any code for the first time then a global execution context is being created. And push into the call stack. So when setTimout() is encountered then it will not be pushed directly into the callstack. It would be stored inside the WebAPIs environment.

Because setTimout() function is not a part of JavaScript it is an API provided by the browser to interact with the outer environment. So setTimeout is part of the web browser not a part of JavaScript.

When setTimeout is encountered by the JavaScript engine then it would be stored inside the WebAPIs environment and the JS engine will continue executing the next line of code. So console.log(“Hello World!) is executed first. Since we have executed everything in global scope then global execution context would come out of the call stack.

When the timer of 5 seconds would be expired then the setTimeout would come inside the task queue.

Then event loops come into the play, the event loop keeps checking whether our call stack is empty or not. If the call stack is empty and we have a function to execute inside the task queue then it will take that function and push it inside the call stack. Since in our case we have executed everything in the global scope so it would pop out of the call stack and our call stack is empty and a function to execute inside the task queue.

So event loop will take that function from the task queue and will push it inside the call stack. As a result “Welcome to GFG” would be printed after 5 seconds.

setTimeout() function: It is an API provided by the browser to interact with the outer environment. It would only be executed once we have completed executing everything inside the global scope then it would be pushed inside the call stack and hence executed.

Example:

Javascript




function print() {
    for(let i = 0; i <= 5; i++) {
        setTimeout(() => {
            console.log(i);
        }, 2000);
    }
}
print();


Output:

0
1
2
3
4
5

setInterval() function: It is used to execute the function repeatedly after a given time period. We need to stop this function, otherwise, it will keep executing it.

Example:

Javascript




var count = 1;
function print() {
    console.log(count);
    count++;
}
setInterval(print, 2000);


In this case, it will keep printing the value of i. It will not stop. We need to explicitly stop it using clearInterval( ) function.

Stopping the setInterval function:

Javascript




var count = 1;
function print() {
    console.log(count);
    count++;
    if(count == 6) {
        clearInterval(id);
    }
}
  
let id = setInterval(print, 2000);


Output:

1
2
3
4
5

clearTimeout() function: It is used to stop the setTimeout function. Just like clearInterval( ) function is used to stop the setInterval function we can use clearTimeout function to cancel the setTimeout function from execution.

Javascript




function sayHello() {
    console.log("Hello world!");
}
function stopTimer() {
    clearTimeout(id);
}
const id = setTimeout(sayHello, 2000);
console.log("This should be executed first");
stopTimer();


Output:

This should be executed first

clearTimeout( ) function has stopped the execution of setTimeout( ) function.

clearInterval function: As we know, the setInterval function keeps executing the function after a particular interval of time. We need to stop it. To stop the setInterval function, we use the clearInterval function.

Example:

Javascript




var count = 1;
function sayHelloWorld() {
    console.log("Hello World!");
    count = count+1;
    if(count == 6) {
        clearInterval(id);
    }
}
let id = setInterval(sayHelloWorld, 2000);


Output:

Hello World!
Hello World!
Hello World!
Hello World!
Hello World!


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads