Timing Events in Javascript
Last Updated :
21 Jun, 2021
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' object or without it. The various timing events are listed below:
setTimeout() Method: This method is used to execute a piece of code after a certain amount of time. Most of the time, this piece of code is written within a function. The function is either passed as a parameter or as an anonymous function directly as a parameter. It returns a positive integer which represents the ID of the timer created due to the call of the setTimeout method. It is optional to use a variable to store the ID but depends on the cases when we want to cancel the timer using the clearTimeout() method.
The function passed is executed after the timer stops. The parameters passed (specified after the delay time) are optional and are accessible to this function. The delay is the time for which the timer has to wait for the function execution. It is written in milliseconds, so ‘1000’ represents ‘1’ second.
Syntax:
let timeoutID = scope.setTimeout(function, delay, param1, param2, ...)
The below example demonstrates the setTimeout() method:
Example:
HTML
<!DOCTYPE html>
<html>
<body style="text-align:center;">
<h1 style="color:#378E47;">
GeeksforGeeks
</h1>
<h2>setTimeout() method</h2>
<p>Click the button and wait for 3 seconds.</p>
<!-- Setting the onclick method for the button -->
<button onclick="setTimeout(geeksforgeeks, 3000);">
Press me
</button>
<h2 style="font-size:3em;color:#378E47;"></h2>
<script>
function geeksforgeeks() {
// Fetching the first index h2 element
var h2Heading =
document.getElementsByTagName("h2")[1];
// Changing the innerHTML tag of the
// fetched h2 heading
h2Heading.innerHTML = "Welcome here!";
}
</script>
</body>
</html>
Output:
clearTimeout() Method: The 'clearTimeout()’ method is used to cancel a timeout established using the setTimeout() method. This method stops the execution of the function passed as a parameter if it is called within the time delay specified in the setTimeout() method.
It accepts a single parameter which is the timoutID that the setTimeout() method returns. An invalid ID passed to this method will not do anything.
Syntax:
scope.clearTimeout(timeoutID)
The below example demonstrates the clearTimeout() method:
Example:
HTML
<!DOCTYPE html>
<html>
<body style="margin-left:50px;">
<h1 style="color:#378E47;">
GeeksforGeeks!
</h1>
<h2>clearTimeout() method</h2>
<p>Press the first button and wait 4 seconds.</p>
<p>
Press the second button before 4 seconds to
prevent the first button to execute.
</p>
<button style="margin-right:10px"
onclick="startFunction()">Press me
</button>
<button onclick="stopFunction()">Stop</button>
<h1 style="font-size:3em; color: #378E47;"></h1>
<!-- Javascript Code -->
<script>
var setTimeoutID;
function startFunction() {
setTimeoutID = setTimeout(function () {
// Fetching the first indexed h1 element
var h2Heading =
document.getElementsByTagName("h1")[1];
// Changing the innerHTML tag of the
// fetched h2 heading
h2Heading.innerHTML = "Welcome here!";
}, 4000);
}
function stopFunction() {
clearTimeout(setTimeoutID);
}
</script>
</body>
</html>
Output:

setInterval() Method: This method is used to repeatedly execute a piece of code within a fixed time interval between each call. The meaning and use of each of the parameters are the same as that of the setTimeout() method. It returns a positive integer which represents the ID of the timer created due to the call of the setTimeout method. It is optional to use a variable to store the ID but depends on the cases when we want to cancel the timer using the clearInterval() method.
The parameters passed (specified after the delay time) are optional and are accessible to the function. The delay is the time that decides how often the function passed as a parameter is executed. It is written in milliseconds, so ‘1000’ represents ‘1’ second.
Syntax:
var intervalID = scope.setInterval(function, delay, param1, param2, ...)
clearInterval() Method: This method is used to cancel the repeating timed action established using the setInterval() method. This method stops the execution of the function passed as a parameter if it is called before all the intervals of the setInterval() method are over.
It accepts a single parameter which is the intervalID that the setInterval() method returns. An invalid ID passed to this method will not do anything.
Syntax:
scope.clearInterval(intervalID)
The below example demonstrates the clearInterval() method:
Example:
HTML
<!DOCTYPE html>
<html>
<body style="text-align:center; color:#378E47;">
<h1> GeeksforGeeks Counter.</h1>
<h2 style="font-size:5em;">10</h2>
<!-- Setting the onclick method for the button -->
<button onclick="geeksforgeeksCounter()">
Press me
</button>
<!-- JavaScript code -->
<script>
// Variable for maintaining count of the timer
let count = 10;
function geeksforgeeksCounter() {
// Fetching the 0th indexed h2 element
var h2Heading =
document.getElementsByTagName("h2")[0];
var countDownID = setInterval(function () {
count--;
h2Heading.innerHTML = count;
if (count <= 0) {
// Changing the innerHTML tag of
// the fetched h2 heading.
h2Heading.innerHTML = "Welcome here!";
// Stop the timer
clearInterval(countDownID);
}
}, 1000);
}
</script>
</body>
</html>
Output:
Other Key Points:
- The setTimeout() and setInterval() methods share the same pool for storing IDs, which means that we can use the clearTimeout() and clearInterval() methods interchangeably. However, we should avoid doing so.
- The browsers that support the setTimeout() and setInterval() methods are mainly, Google Chrome, Internet Explorer, Safari, Opera, and Firefox.
- When you don’t need to use the clearTimeout() or clearInterval() method, then there is no need to store the ID returned by the setTimeout() or setInterval() method respectively.
Similar Reads
Event Queue in JavaScript
JavaScript, being single-threaded, processes tasks sequentially, meaning it executes one task at a time. This can pose a challenge when dealing with operations that take time to complete, such as fetching data from a server or performing complex calculations. To handle such scenarios efficiently, Ja
5 min read
Mutlithreading in JavaScript
Multithreading is the ability of any program to execute multiple threads simultaneously. As we know JavaScript is a single-threaded programming language, which means it has a single thread that handles all the execution sequentially. Single-threaded means one line of code run at once. Originally, Ja
3 min read
JavaScript Date setTime() Function
The JavaScript Date setTime() Function is a built-in Function in Javascript that is used to get a date object by adding given milliseconds to the date 01/01/1970 Syntax: date.setTime(milliseconds) Parameters: setTime() Function takes parameters as follows. milliseconds: Number of milliseconds to add
2 min read
What is An Event Loop in JavaScript?
The event loop is an important concept in JavaScript that enables asynchronous programming by handling tasks efficiently. Since JavaScript is single-threaded, it uses the event loop to manage the execution of multiple tasks without blocking the main thread.JavaScriptconsole.log("Start"); setTimeout(
4 min read
Explain the working of timers in JavaScript
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
5 min read
How to Detect Idle Time in JavaScript ?
The idle time is the time that the user doesn't interact with a web page. This interaction can be either moving the mouse, clicking on the page, or using the keyboard. This time can be detected to execute certain events that may need to occur after a certain period of idle time. \ Method 1: Using Ja
4 min read
How to Get Current Time in JavaScript ?
This article will show you how to get the current time in JavaScript. Whether you are creating a digital clock, scheduling events, or simply logging timestamps, knowing how to retrieve the current time is essential. Here, we will cover different methods to get the current time in JavaScript.Table of
2 min read
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
JavaScript Timer
A timer has been shown that shows the countdown, and its color/message gets changed after every specific period. Prerequisites: GetMinutes()GetSeconds()SetInterval() MethodSyntax: setTimeout(function, milliseconds, parameter1, ...);Parameter:AttributeDescriptionfunctionIt is the function that will b
2 min read
Debouncing in JavaScript
In JavaScript, debouncing is a technique used to ensure that a function is not called too frequently. It is commonly used in scenarios where events are triggered rapidly, such as typing in an input field or resizing a window. Without debouncing, functions might be executed many times in quick succes
6 min read