Explain the working of timers in JavaScript
Last Updated :
27 Mar, 2022
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!
Similar Reads
Finding the time elapsed in JavaScript
In this article, we are going to find out the time elapsed between the two-time instances using the Date object of JavaScript. So firstly we will see what is Date object in JavaScript in short. Date Object: A JavaScript Date object deal with dates and times and it is a built-in object. It stores a v
4 min read
Understanding the Async in JavaScript
Definition: Async is a short form for âasynchronousâ. Synchronous means executing statements one after the other which implies the next statement will get executed only after the previous statement is executed completely. Whereas in Asynchronous calls the next statement gets executed without even wa
4 min read
Explain the working of Node.js
Welcome to the world of Node.js, an open-source runtime environment that has transformed the landscape of backend development. Traditionally, JavaScript was confined for frontend development, powering user interactions on the browser. However, with the advent of Node.js, JavaScript has broken free f
4 min read
How to Set Time Delay in JavaScript?
Delaying the execution of code is a fundamental technique that is commonly used in JavaScript for tasks like animations, API polling, or managing time intervals between actions. JavaScript provides several built-in methods to set time delays: setTimeout() and setInterval(). We can set time delay in
2 min read
How to Get the Timestamp in JavaScript?
A timestamp is a numeric representation of the current time. It is a unique identifier that marks the exact moment when an event occurred or when a certain action was performed. 1. Using Date.now() MethodThis approach uses Date.now() method. This method returns the number of milliseconds since Janua
2 min read
Timing Events in Javascript
Timing events are the events that help to execute a piece of code at a specific time interval. These events are directly available in the HTML DOM (Document Object Model) Window object, i.e., they are present in the browser. So, these are called global methods and can be invoked through the 'window'
5 min read
Explain Scope and Scope Chain in JavaScript
In this article, we will try to understand what is the scope of a variable as well as its function (or method). We will see what is a Scope Chain with the help of certain coding examples. ScopeScope in JavaScript determines the accessibility of variables and functions at various parts of one's code
5 min read
Explain Promise.race() with async-await in JavaScript
In this article, we will try to understand how we may implement Promise.race() method with async-await in JavaScript with the help of certain coding examples as well as theoretical explanations. Let us first quickly understand how we may implement Promise.race() method. This method is one of the mos
3 min read
JavaScript Responsive time of an event
Responsive time of an event is the time taken to load the result of that event and the time taken to start that event. In this post, various shapes have been used using Math.random() function. The task is to find out the responsive time of changing these shapes. As soon as you click the shape, it ge
2 min read
How to count the number of times a button is clicked using JavaScript ?
At times, it becomes necessary to monitor the number of times a user clicks a button. In this article, we are going to learn how to count the number of times a button is clicked using JavaScript Below are the approaches to count the number of times a button is clicked using JavaScript Table of Conte
3 min read