36

I want to delay execution in betwen the follwoing codes:

$("#myName").val("Tom");
///delay by 3s
$("#YourName").val("Jerry");
//delay by 3s

$("#hisName").val("Kids");
Adnan
  • 23,948
  • 17
  • 75
  • 108
learning
  • 10,375
  • 33
  • 84
  • 152

4 Answers4

73

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

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
4

You can use the setTimeout function. I think the syntax is

window.setTimeout('$("#YourName").val("Jerry")',3000);
Jad
  • 912
  • 8
  • 14
  • 5
    To paraphrase the Dalai Lama: Never use strings with `setTimeout` if you can avoid it. You can always avoid it. – T.J. Crowder May 13 '11 at 10:45
  • He's the wisest :) You're right, I should have put a disclaimer about putting js code in strings. – Jad May 13 '11 at 12:26
  • Why can't we put quotes? Which quote are you talking about? The one wrapping the jQuery block or? – Vennsoh Dec 03 '13 at 11:11
  • The quotes mean we are passing a javascript string to setTimeout. In T.J Crowder answer above an anonymous function is passed. This is a much better approach. Using a function is more readable and robust, for example a syntax error would be detected right away. You can check the discussions on the eval statement for more information. – Jad Dec 03 '13 at 13:18
2

If delay is always the same (3s in your example), you may avoid nested code and use setInterval instead of setTimeout:

var i
  , ids = ["myName", "YourName", "hisName"]
  , names = ["Tom", "Jerry", "Kids"];

i = setInterval(function () {
    if (ids.length > 0) {
        $("#" + ids.shift()).val(names.shift());
    } else {
        clearInterval(i);
    }
}, 3000);
nilfalse
  • 2,244
  • 2
  • 18
  • 15
2

You cannot "delay" in JavaScript without locking the browser; i.e the user cannot move their mouse or click anything (undesirable for 3+ seconds!).

Instead, you should look at setting a timeout, which will execute designated code some time in the future...

$("#myName").val("Tom");
setTimeout(function () {
    $("#YourName").val("Jerry");

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

You can check out the documentation for setTimeout here: https://developer.mozilla.org/en/window.setTimeout. The basics of it is that you pass either a function reference, or a string (which should be avoided however), as the first parameter, with the second parameter specifying how many milliseconds the code should be delayed for.

Matt
  • 70,063
  • 26
  • 142
  • 172