javascript 超时/睡眠使用 setTimeout()

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

javascript timeout/sleep using setTimeout()

javascriptjquerytimeoutsleeptiming

提问by Jay

How can I set a 2 second timeout to wait for page controls to be populated? I want to use javascript I have tried the following but to no avail:

如何设置 2 秒超时以等待填充页面控件?我想使用 javascript 我尝试了以下但无济于事:

setTimeout(function(){},2000);

setTimeout(2000);

Anyone able to provide a pointer?

任何人都可以提供一个指针?

回答by Coop

setTimeout(function(){
  //put your code in here to be delayed by 2 seconds
},2000);

The code you want to delay needs to sit inside the setTimeout function.

您想要延迟的代码需要位于 setTimeout 函数内。

回答by Suresh Atta

Try like this

像这样尝试

$('input').click(function () {
    var that = $(this);
    setTimeout(function() { alertMsg(that); },2000);
});

DEMO

演示

回答by Craig Hicks

NOTE: Part of this answer is identical to another more popular answer, but this answer also includes output to make clear that the constructed sleep()permits independent loops in the same thread to run interleaved.

注意:此答案的一部分与另一个更受欢迎的答案相同,但此答案还包括输出,以明确构造sleep()允许同一线程中的独立循环交错运行。

ECMAScript Latest Draft (ECMA-262). As of 2019, supported in most broswers, but not IE.

ECMAScript 最新草案 (ECMA-262)。截至 2019 年,大多数浏览器都支持,但不支持 IE。

function sleep(n) { return new Promise(resolve=>setTimeout(resolve,n)); }

async function LoopA() {
    for (let i=0;i<10;i++) {
        console.log("LoopA i=",i,
                    ",sec=",performance.now().toFixed(0)/1000);
        await sleep(1000);
    }
}
async function LoopB() {
    for (let i=0;i<10;i++) {
        console.log("LoopB i=",i,
                    ",sec=",performance.now().toFixed(0)/1000);
        await sleep(1000);
    }
}
LoopA();
LoopB();

has sample output:

有样本输出:

LoopA i= 0 ,sec= 1648.665 
LoopB i= 0 ,sec= 1648.665 
LoopA i= 1 ,sec= 1649.666
LoopB i= 1 ,sec= 1649.667
LoopA i= 2 ,sec= 1650.667
LoopB i= 2 ,sec= 1650.669
LoopA i= 3 ,sec= 1651.669
LoopB i= 3 ,sec= 1651.67
LoopA i= 4 ,sec= 1652.67
LoopB i= 4 ,sec= 1652.671
LoopA i= 5 ,sec= 1653.671 
LoopB i= 5 ,sec= 1653.672 
LoopA i= 6 ,sec= 1654.672 
LoopB i= 6 ,sec= 1654.674 
LoopA i= 7 ,sec= 1655.674 
LoopB i= 7 ,sec= 1655.675 
LoopA i= 8 ,sec= 1656.675 
LoopB i= 8 ,sec= 1656.676 
LoopA i= 9 ,sec= 1657.677 
LoopB i= 9 ,sec= 1657.678