简体   繁体   中英

How to wait for a period of time after a function run

If I have a function which I would like my js code to run it immediately but after the run, wait for 2 seconds. How to achieve this logic?

( Note: It is just the inverse logic compare with setTimeout() , since setTimeout( ) first wait a certain amount of time then execute the function.)

Just put your code inside an anonymous function passed to setTimeout.

eg

functionToRunFirst();
setTimeout(function() {
    // rest of code here
}, 2000);

I think what you're looking for is a method to suspend the execution of the code until a timeout. Many amateur programmers wish for such a construct, but it doesn't exist in JavaScript. It's not needed. For all purposes in JavaScript setTimeout and setInterval are perfect candidate solutions.

However, JavaScript is a powerful language. You can build your own construct to address this issue. Take a look at Neil Mix's blog post . With his approach you can create a sleep function which can be used along the following lines (note that currently only Firefox supports JavaScript 1.7):

function mainGeneratorFunction() {
    functionToRunFirst();
    yield sleep(2000);
    //rest of the code
}

However, for other browsers don't despair. You can use a hack known as XHR Sleeping . In this approach you simply use a synchronous XMLHttpRequest to call a server side script like php, which then sleeps for the specified time and returns after it wakes up. The JavaScript code is as follows:

function sleep(microseconds) {
    var request = new XMLHttpRequest();
    request.open("GET", "sleep.php?time=" + microseconds, false);
    request.send();
}

functionToRunFirst();
sleep(2000000);
//rest of the code

The php sleep function is as follows:

<?php
    usleep($_GET["time"]);
?>

using setTimeout is one way to do it

function run() {    
    // run this code

    setTimeout(afterTwoSeconds, 2000);    
}

function afterTwoSeconds() {    
    // run this code two seconds after executing run.   
}

// call run
run();

given some filling out on your part, this should run 5 times with half a second timer

var counter = 0;
var arrayOfPicture = []; //fill this out

function gifSimulator() {

    //use the counter as an index in the array, and change the image source of your element with that.


    if (counter < 5) {

        setTimeout(function () {

            counter++;

            gifSimlulator();

        }, 500); //lets wait half a second
    }
}

what does "wait for 2 seconds" mean? do you mean you want to block a return from the function for 2 seconds?

if so, you can't do that. there is no sleep() function in JavaScript.

you'll have to just use setTimeout()

Nothing wrong with the answers above, but a different way is:

 $("#somethingThatDoesntExist").fadeTo(2000, 1, function() { // two seconds later });

I don't know why you guys going these much. I believe we can do it using Date object. Take the date value first and use setInterval function to wait until we get specified interval (get new Date and check for difference). Once we get that reset the interval function and proceed with your code after that can run.

function when(wait,then,timer) {
    var timer = timer || 1;
    var interval = setInterval(function(){
        if(!wait()) {
            clearInterval(interval);
            if(Array.isArray(then) && then.length > 0) {
              return when(then.shift(),then,timer);
            }
            return then();
        }
    }, timer);
}

This function will recursively trigger one function after the other in sequence when the prior function returns false.

 function when(wait,then,timer) { var timer = timer || 1; var interval = setInterval(function(){ if(!wait()) { clearInterval(interval); if(Array.isArray(then) && then.length > 0) { return when(then.shift(),then,timer); } return then(); } }, timer); } var age = 0; function grow() { age++; } function say(word) { document.body.innerHTML += ('Age: ' + age + ' = ' + word + '<br>'); } function born() { grow(); say('hey'); return age < 2; } function young() { grow(); say('play'); return age < 20; } function old() { grow(); say('pay'); return age < 70; } function elderly() { grow(); say('grey'); return Math.random()*age < 80; } function dying() { grow(); say('pray'); return Math.random()*age < 100; } function dead() { say('decay'); return null; } when(born,[young,old,elderly,dying,dead]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM