Open In App

JavaScript setTimeout() & setInterval() Method

Last Updated : 20 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript SetTimeout and SetInterval are the only native function in JavaScript that is used to run code asynchronously, it means allowing the function to be executed immediately, there is no need to wait for the current execution completion, it will be for further execution.

JavaScript setTimeout() Method

This method executes a function, after waiting a specified number of milliseconds. 

Syntax:

window.setTimeout(function, milliseconds);

Parameter:

  • function: the first parameter is a function to be executed
  • milliseconds: which indicates the number of milliseconds before the execution takes place.

Example: If, we want an alert box to pop up, 2 seconds after the user presses the click me button. 

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport">
    <title>Document</title>
</head>
 
<body>
    <button onclick="setTimeout(gfg, 2000);">
        Press me
    </button>
    <script>
        function gfg() {
            alert('Welcome to GeeksforGeeks');
        }
    </script>
</body>
 
</html>


Output: As soon as the user presses the “press me” button, after a pause of 2 seconds this message alert box will pop up.

We can even stop the execution of the setTimeout() function by using a method called as clearTimeout().

Syntax: 

window.clearTimeout(value);

Parameter:

  • value: The function whose execution is to be stopped.

The clearTimeout() method should only be used if the function has not been executed. Let us see an example below

Example: In this example, we will use a setTimeout() function and stop its execution using the clearTimeout() function before the execution of the setTimeout().

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport">
    <title>Document</title>
</head>
 
<body>
    <p>Press the stop button
        before the alert is shown</p>
    <button onclick="val = setTimeout(gfg, 2000);">
        Press me
    </button>
    <button onclick="clearTimeout(val);">
        Stop Execution</button>
    <script>
        function gfg() {
            alert('Welcome to GeeksforGeeks');
        }
    </script>
</body>
 
</html>


Output: Here if we click the stop execution button before the alert is shown, the execution of the alert is stopped.

JavaScript setInterval() Method

The setInterval() method repeats a given function at every given time interval. 

Syntax:

window.setInterval(function, milliseconds);

Parameter: There are two parameters that accepted by this method

  • function: the first parameter is the function to be executed
  • milliseconds: indicates the length of the time interval between each execution.

Example: In this example, we are using setInterval() method.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport">
    <title>Document</title>
</head>
 
<body>
    <p id="GFG"></p>
    <script>
        let myVar = setInterval(myTimer, 1000);
 
        function myTimer() {
            document.getElementById("GFG")
                .innerHTML += "<p>Hi</p>";
        }
    </script>
</body>
 
</html>


Output: After every second a new “hi” message will be displayed.

Since the setInterval() method executes the function infinitely hence there is a method called as clearInterval() to stop the execution of the setInterval().

Syntax: 

window.clearInterval(value);

Parameter: 

  • value: The function whose execution is to be stopped.

Example: In this example, we will first execute a setInterval() function and then stop its execution by using the clearInterval() function.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport">
    <title>Document</title>
</head>
 
<body>
    <p id="GFG"></p>
    <button onclick="clearInterval(myVar)">
        Stop Execution</button>
 
    <script>
        let myVar = setInterval(myTimer, 1000);
 
        function myTimer() {
            document.getElementById("GFG")
                .innerHTML += "<p>Hi</p>";
        }
    </script>
</body>
 
</html>


Output: When the stop button is clicked the execution is stopped.

Supported Browser:

  • Google Chrome 1 and above
  •  Edge 12 and above
  • Internet Explorer 4 and above
  • Firefox 1 and above
  • Opera 4 and above
  • Safari 1 and above

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.



Similar Reads

Difference Between setTimeout & setInterval in JavaScript
JavaScript has both setTimeout and setInterval functions that are used for executing code after a certain delay. However, they differ in how they handle the timing of execution. Understanding their differences is crucial for effectively managing asynchronous operations in our code which is explained below: Table of Content Using setTimeoutUsing set
2 min read
Difference Between setTimeout & setInterval
JavaScript provides two essential functions: setTimeout and setInterval. While both serve similar purposes, they have distinct differences that developers should be aware of to effectively manage timing-related tasks in their code. setTimeout() methodA built-in JavaScript function called setTimeout allows you to run a function or evaluate an expres
3 min read
How to Change the Time Interval of setinterval() Method at RunTime using JavaScript ?
In this article, we are going to learn how to change the setInterval() time after running one element. The setInterval() method reads the timing once and invokes the function at regular intervals. There are two methods to solve this problem which are discussed below: Using clearInterval() methodUsing the setTimeout() method. Method 1: Using clearIn
3 min read
JavaScript setInterval() Method
JavaScript setInterval() method is used to repeatedly execute a given function at specified intervals. The setInterval() method continues calling the function until clearInterval() is called or the window is closed. Important Note: setTimeout() is for executing a function once after a specified delay.setInterval() is for executing a function repeat
2 min read
How to execute setInterval function without delay for the first time in JavaScript ?
The setInterval() method always invokes the function after the delay for the first time using two approaches: Method 1: Calling the function once before executing setInterval: The function can simply be invoked once before using the setInterval function. This will execute the function once immediately and then the setInterval() function can be set
2 min read
How to trigger setInterval loop immediately using JavaScript ?
This article will show some simple ways in which the setInterval() method can be made to execute the function without delay. There are many procedures to do so, below all the procedures are described with the example. Note: In this article setInterval() method will start immediately for the 1st time run. Below examples illustrate the above approach
2 min read
setInterval() function in JavaScript
The setInterval function in JavaScript is used for repeatedly executing a specified function or code block at fixed intervals. It can be used for creating periodic tasks, animations, and real-time updates in web applications. It is essential to note that intervals set by setInterval are not guaranteed to be precise due to the single-threaded nature
2 min read
How to stop setInterval Call in JavaScript ?
In JavaScript, the setInterval() function is used to repeatedly execute a specified function at a fixed interval. However, there may be scenarios where we need to stop the execution of setInterval() calls dynamically. Stopping a setInterval() call in JavaScript is essential to prevent ongoing repetitive tasks and manage resource usage efficiently.
2 min read
What is the use of setInterval() method in Node.js ?
The setInterval() method helps us to repeatedly execute a function after a fixed delay. It returns a unique interval ID which can later be used by the clearInterval() method which stops further repeated execution of the function. Syntax: const intervalId = setInterval(func, [delay, arg1, agr2, ..., argN]); where, func is the function that we want t
3 min read
How to use setInterval() method inside React components ?
The setInterval() method executes a function repeatedly at a specified interval. We can use the setInterval method in a React component to update the component's state or perform other actions. Syntax : //Implementing the setInterval methodconst interval = setInterval(() =&gt; { setState(state + 1);}, 1000);However, there are a few caveats to be aw
3 min read
Practice Tags :