简体   繁体   English

JavaScript中的setTimeout不起作用

[英]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! 但是基本上,只要我按一下按钮,警报就会触发,根本没有5秒的延迟!

<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>
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 查看MDN参考以获取有关如何使用setTimeout更多信息。

The setTimeout function is used as follows: setTimeout函数的用法如下:

setTimeout(<function>, <delay>);

The first parameter is a function. 第一个参数是一个函数。 What you're doing is giving it the value of alert(..); 您正在做的就是为其赋予alert(..)的值;

Change it to: 更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM