5

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?

Jay
  • 3,012
  • 14
  • 48
  • 99
  • 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 Aug 15 '13 at 13:53

3 Answers3

13
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.

CaribouCode
  • 13,998
  • 28
  • 102
  • 174
0

Try like this

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

DEMO

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

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
Craig Hicks
  • 2,199
  • 20
  • 35