Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

jquery - How to delay execution in between the following in my javascript

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");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...