How to delay execution in between the following in my javascript

You can use setTimeout for that:

setTimeout(function() {
    // Your code here
}, delayInMilliseconds);

E.g.:

$("#myName").val("Tom");

/// wait 3 seconds
setTimeout(function() {
    $("#YourName").val("Jerry");

    /// wait 3 seconds
    setTimeout(function() {
        $("#hisName").val("Kids");
    }, 3000);
}, 3000);

setTimeout schedules a function to be run (once) after an interval. The code calling it continues, and at some point in the future (after roughly the time you specify, though not precisely) the function is called by the browser.

So suppose you had a function called output that appended text to the page. The output of this:

foo();
function foo() {
    var counter = 0;

    output("A: " + counter);
    ++counter;
    setTimeout(function() {
        output("B: " + counter);
        ++counter;
        setTimeout(function() {
            output("C: " + counter);
            ++counter;
        }, 1000);
    }, 1000);
    output("D: " + counter);
    ++counter;
}

…is (after a couple of seconds):

A: 0
D: 1
B: 2
C: 3

Note the second line of that. The rest of foo‘s code runs before either of the scheduled functions, and so we see the D line before the B line.

setTimeout returns a handle (which is a non-zero number) you could use to cancel the callback before it happens:

var handle = setTimeout(myFunction, 5000);
// Do this before it runs, and it'll never run
clearTimeout(handle);

There’s also the related setInterval / clearInterval which does the same thing, but repeatedly at the interval you specify (until you stop it).

Leave a Comment