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
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Introduction to JavaScript JavaScript is a versatile, dynamically typed programming language used for interactive web applications, supporting both client-side and server-side development, and integrating seamlessly with HTML, CSS, and a rich standard library.JavaScript is a single-threaded language that executes one task at
7 min read
JSON Web Token (JWT) A JSON Web Token (JWT) is a standard used to securely transmit information between a client (like a frontend application) and a server (the backend). It is commonly used to verify users' identities, authenticate them, and ensure safe communication between the two. JWTs are mainly used in web apps an
7 min read
Frontend Developer Interview Questions and Answers Frontend development is an important part of web applications, and it is used to build dynamic and user-friendly web applications with an interactive user interface (UI). Many companies are hiring skilled Frontend developers with expertise in HTML, CSS, JavaScript, and modern frameworks and librarie
15+ min read
JavaScript Coding Questions and Answers JavaScript is the most commonly used interpreted, and scripted Programming language. It is used to make web pages, mobile applications, web servers, and other platforms. Developed in 1995 by Brendan Eich. Developers should have a solid command over this because many job roles need proficiency in Jav
15+ min read
Top 95+ Javascript Projects For 2025 JavaScript is a lightweight, cross-platform programming language that powers dynamic and interactive web content. From real-time updates to interactive maps and animations, JavaScript brings web pages to life.Here, we provided 95+ JavaScript projects with source code and ideas to provide hands-on ex
4 min read
Functions in JavaScript Functions in JavaScript are reusable blocks of code designed to perform specific tasks. They allow you to organize, reuse, and modularize code. It can take inputs, perform actions, and return outputs.JavaScriptfunction sum(x, y) { return x + y; } console.log(sum(6, 9)); // output: 15Function Syntax
5 min read
JavaScript Exercises, Practice Questions and Solutions JavaScript Exercise covers interactive quizzes, tracks progress, and enhances coding skills with our engaging portal. Ideal for beginners and experienced developers, Level up your JavaScript proficiency at your own pace. Start coding now! A step-by-step JavaScript practice guide for beginner to adva
3 min read
HTML DOM (Document Object Model) The HTML DOM (Document Object Model) is a programming interface that represents the structure of a web page in a way that programming languages like JavaScript can understand and manipulate. Think of it as a tree of objects where each part of your HTML document (elements, attributes, text) is repres
6 min read