Search code examples
javascripthtmldelay

setTimeout in JavaScript doesn't work


Strange issue here, I don't see why it isn't working. But basically the alert is fire as soon as I press the button, there is no 5 second delay at all!

<html>
<head>
    <title>Testing Page</title>
</head>
<script type="text/javascript">
function testing() {
    var delay = 5000;
    setTimeout(alert("5 seconds later..."),delay);  
}
</script>
<body>
<input type="button" value="Run Function" onClick="testing()">
</body>
</html>

Solution

  • function testing() {
        var delay = 5000;
        setTimeout(function(){alert("5 seconds later...");},delay);  
    }
    

    Need to wrap it in a function so the alert is not immediately executed.

    Check out the MDN reference for more information regarding how to use setTimeout