Javascript setTimeout and clearTimeout method with example

Sometimes, you may want to execute Javascript code after a specific time. This is useful when you want to wait for specific event complete before code executes. For example, you want to send request after 1 second of user stop typing. This is required to send request to server only after user complete to typing keywords instead of sending request on every character.

In this example, we will discuss on how you can execute Javascript code after certain time. We will also discuss how you can prevent to run code which were set on setTimeout method.

setTimeout method

The setTimeout method executes specified function or piece of code after specific given time.

Syntax

setTimeout(function, milliseconds, arg1, arg2, ...)

Where:

function which executes after timer expires.
milliseconds optinal is time expires it
arg1, arg2 optional parameters pass in the function.

Example:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>setTimeout method</title>
</head>
<body>
    <script type="text/javascript">
        setTimeout(function() {
            alert('Hello World!');
        }, 2000);
    </script>
</body>
</html>

clearTimeout method

clearTimeout method cancels the code to be execute set in setTimeout method.

Syntax:

clearTimeout(setTimeoutVariable)

Where:
setTimeoutVariable is the variable defined for setTimeout method.

This is useful to stop executing code set in setTimeout method. For example, stop to send request server when user start typing before request was send.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>clearTimeout method</title>
</head>
<body>
    <button onclick="createAlert()">Alert</button>
    <button onclick="stopAlert()">Stop Alert</button>
    <script type="text/javascript">
        var newAlert;
        function createAlert() {
            newAlert = setTimeout(function() {
                alert('Hello World!.');
            }, 5000);
        }

        function stopAlert() {
            clearTimeout(newAlert);
        }
    </script>
</body>
</html>

So far in this article, we have learn how to execute Javascript code after a specific time. We have also learned to prevent executing code set in setTimeout method. I hope you liked the article.

Tags:

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

No Comment