WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES

How to Set Time Delay in JavaScript

Topic: JavaScript / jQueryPrev|Next

Answer: Use the setTimeout() Function

You can use the setTimeout() function to set time delay before executing a script in JavaScript. This is a reliable way to put time delay without blocking the UI since it is an asynchronous function.

Let's try out the following example to understand how it basically works:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Execute Script after a Delay in Javascript</title>
</head>
<body>
    <p>If you click the button alert will show after 2 seconds</p>
    <button type="button" onclick="showAlert();">Show Alert</button>
    
    <script>
    function showAlert(){      
        var delayInMilliseconds = 2000; // 2 seconds

        setTimeout(function() {
            alert("Hi there!");
        }, delayInMilliseconds);
    }
    </script>
</body>
</html>

Related FAQ

Here are some more FAQ related to this topic:

Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties