最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - javascript timeoutsleep using setTimeout() - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Aug 15, 2013 at 13:52 JayJay 3,08216 gold badges52 silver badges105 bronze badges 1
  • 1 whatever you want to do after the timeout has to be inside the callback function passed to setTimeout() as in the first example you have given – Arun P Johny Commented Aug 15, 2013 at 13:53
Add a comment  | 

3 Answers 3

Reset to default 14
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.

Try like this

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

DEMO

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
发布评论

评论列表(0)

  1. 暂无评论