javascript timeout/sleep using setTimeout()

此生再无相见时 提交于 2021-02-16 14:41:49

问题


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:

setTimeout(function(){},2000);

setTimeout(2000);

Anyone able to provide a pointer?


回答1:


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.




回答2:


Try like this

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

DEMO




回答3:


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.

ECMAScript Latest Draft (ECMA-262). As of 2019, supported in most broswers, but not 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


来源:https://stackoverflow.com/questions/18254168/javascript-timeout-sleep-using-settimeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!