为什么alert()
之后setTimeout()
未按预期调用?为什么`setTimeout()`后面的alert()没有按预期调用?
function run() {
setTimeout('', 5000)
alert('Welcome!')
}
run()
为什么alert()
之后setTimeout()
未按预期调用?为什么`setTimeout()`后面的alert()没有按预期调用?
function run() {
setTimeout('', 5000)
alert('Welcome!')
}
run()
setTimeout('', 5000)
不会做任何事情。它不会延迟下一行代码,如果这是你正在做的事情,并且为第一个参数指定一个空字符串,那么在setTimeout()
实际上没有启动时你没有给它任何代码来运行,所以它什么都不做。
如果您希望告警在5秒内开火,然后你这样做:
setTimeout(function() {
alert("Welcome!");
}, 5000);
如果你想在页面加载后,警报弹出,那么你需要挂钩到表示页面已加载的事件,或者仅在</body>
标记之前将您的警报放置在<script>
标记内。
<html>
<body>
your HTML here
<script>
alert("Welcome!");
</script>
</body>
</html>
你为什么不测试它? – undefined
http://jsfiddle.net/Vedant_Terkar/a9zkg/ –