Javascript 窗口加载事件中的Javascript setTimeout函数......不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8047478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:30:38  来源:igfitidea点击:

Javascript setTimeout function in window load event... not working

javascript

提问by Sunil Kumar

I've done this a month before... But now its not working... The code is

我一个月前做过这个......但现在它不起作用......代码是

window.onload = function(){
 setTimeout(function(){
   alert("Hello");
 }, 10000);
};

This is written in script in head of the test.php page. The script and other tags are correct.

这是在 test.php 页面头部的脚本中编写的。脚本和其他标签是正确的。

I would like to call a specific function every 10 seconds. The alert just shows once only. This is problem in every browser.... After this testing i would like to check the url every 2 seconds and call an AJAX function.

我想每 10 秒调用一次特定的函数。警报只显示一次。这在每个浏览器中都是问题.... 在这个测试之后,我想每 2 秒检查一次 url 并调用一个 AJAX 函数。

Any Help??

任何帮助?

回答by James Allardice

That's what setTimeoutdoes (executes once after a specified interval). You're looking for setInterval(calls a function repeatedly, with a fixed time delay between each call to that function):

这就是setTimeout(在指定的时间间隔后执行一次)。您正在寻找setInterval(重复调用一个函数,每次调用该函数之间有固定的时间延迟):

window.onload = function(){
   setInterval(function(){
       alert("Hello");
   }, 10000);
};

回答by Quentin

Use setIntervalinstead.

请改用setInterval

回答by abuduba

var fn = function(){alert("Hello")};

It is possible using setTimeout:

可以使用 setTimeout:

window.onload =  function(){ setTimeout( function(){ fn();window.onload() },10000) };

but the best solution is setInterval:

但最好的解决方案是 setInterval:

window.onload = function() { setInterval(fn,10000)};

回答by MOleYArd

setTimeout is intended for one-time run. Look at setInterval function.

setTimeout 用于一次性运行。看看 setInterval 函数。