睡眠/等待/暂停 javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13658494/
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-10-26 19:23:50  来源:igfitidea点击:

sleep/wait/pause javascript

javascripthtmlparsingsleepwait

提问by Ilya Kharlamov

I'm writing a script for the serial extraction of information from a page, in general I have to pause javascript, but that the page continues to load, and the javascript stopped.

我正在编写一个用于从页面中串行提取信息的脚本,通常我必须暂停 javascript,但页面继续加载,并且 javascript 停止。

setTimeoutis not necessary, since the rest of the script is still running

setTimeout不是必需的,因为脚本的其余部分仍在运行

I need it in order to make the script continues to run after the other script (which I do not have access) download the necessary data to the page (this takes 3 seconds).

我需要它以使脚本在另一个脚本(我无权访问)将必要的数据下载到页面后继续运行(这需要 3 秒)。

P.S. If there is something I pull information from the village - http://www.mosgortrans.org/pass3/using mozilla with extention "user script"

PS如果有什么我从村里提取信息 - http://www.mosgortrans.org/pass3/使用带有扩展“用户脚本”的mozilla

采纳答案by Stuart

As the previous answer and comment have suggested, the normal way of doing this would be to put the code you want to run after the script loads in a function in setTimeout. If you are worried, for instance, about event handlers being triggered while you are waiting and causing an error, then you need to disable the event handlers (e.g. element.onclick = null) then re-enable them within the time-out function. I suppose you could also do something like this:

正如之前的答案和评论所建议的那样,执行此操作的正常方法是将脚本加载后要运行的代码放入setTimeout. 例如,如果您担心在等待时触发事件处理程序并导致错误,那么您需要禁用事件处理程序(例如element.onclick = null),然后在超时功能内重新启用它们。我想你也可以做这样的事情:

var pause = false;
...
callExternalScript();
pause = true;    
setTimeout(function() {
   pause = false;
}, 3000);
...
function oneOfMyOtherFunctions() {
    if (pause) return;
    ...
}
...

but this is messy because you have to include if (pause) returnat the start of every function that you want to disable while the script is paused. Also you may or may not want to add extra code to run all those functions that were called while the script was paused, once it has been un-paused.

但这很麻烦,因为您必须if (pause) return在脚本暂停时要禁用的每个函数的开头包含。此外,一旦脚本被取消暂停,您可能想也可能不想添加额外的代码来运行所有在脚本暂停时调用的函数。

回答by Eric

I don't see why setTimeoutis not necessary here - it does exactly what you describe:

我不明白为什么setTimeout这里没有必要 - 它完全符合您的描述:

setTimeout(function() {
    // this code runs 3 seconds after the page loads
}, 3000);