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 w3wiki');
        }
    </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 w3wiki');
        }
    </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 setTimeout() & setInterval() Method

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.

Similar Reads

JavaScript setTimeout() Method

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

JavaScript setInterval() Method

...