html - setTimeout in JavaScript doesn't work - Stack Overflow

Strange issue here, I don't see why it isn't working. But basically the alert is fire as soon

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>

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>
Share asked Jan 13, 2014 at 2:18 Martyn BallMartyn Ball 4,9059 gold badges63 silver badges145 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8
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

The setTimeout function is used as follows:

setTimeout(<function>, <delay>);

The first parameter is a function. What you're doing is giving it the value of alert(..);

Change it to:

setTimeout(function(){ alert("5 seconds later..."); }, delay);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745069104a4609436.html

相关推荐

  • html - setTimeout in JavaScript doesn&#39;t work - Stack Overflow

    Strange issue here, I don't see why it isn't working. But basically the alert is fire as soon

    15小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信