如何在函数运行后等待一段时间

时间:2011-11-15 09:15:41

标签: javascript jquery javascript-events

如果我有一个函数,我希望我的js代码立即运行,但运行后,等待2秒。如何实现这个逻辑?

注意:这只是与setTimeout()的逆逻辑比较,因为setTimeout()首先等待一段时间然后执行函数。)

8 个答案:

答案 0 :(得分:40)

只需将代码放入传递给setTimeout的匿名函数中。

e.g。

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

答案 1 :(得分:6)

我认为您正在寻找的是一种暂停执行代码直到超时的方法。许多业余程序员都希望有这样的构造,但它在JavaScript中不存在。这不是必需的。出于JavaScript的所有目的,setTimeoutsetInterval都是完美的候选解决方案。

然而,JavaScript是一种强大的语言。您可以构建自己的构造来解决此问题。看看Neil Mix的blog post。通过他的方法,您可以创建一个睡眠功能,可以按照以下几行使用(请注意,目前只有Firefox支持JavaScript 1.7):

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

然而,对于其他浏览器并不绝望。您可以使用称为XHR Sleeping的黑客。在这种方法中,您只需使用同步XMLHttpRequest来调用服务器端脚本,如php,然后在指定的时间内休眠,并在唤醒后返回。 JavaScript代码如下:

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

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

php睡眠功能如下:

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

答案 2 :(得分:3)

使用setTimeout是一种方法

function run() {    
    // run this code

    setTimeout(afterTwoSeconds, 2000);    
}

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

// call run
run();

答案 3 :(得分:1)

“等待2秒”是什么意思?你的意思是你想要阻止函数返回2秒钟?

如果是这样,你不能这样做。 JavaScript中没有sleep()函数。

你必须使用setTimeout()

答案 4 :(得分:1)

上述答案没有错,但另一种方式是:

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

答案 5 :(得分:1)

如果你有一些填写,这应该用半秒计时器运行5次

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
    }
}

答案 6 :(得分:0)

我不知道你们为什么要这么做。我相信我们可以使用Date对象来做到这一点。首先获取日期值并使用setInterval函数等待我们获得指定的间隔(获取新日期并检查差异)。一旦我们重置了interval函数并继续执行代码,就可以运行。

答案 7 :(得分:0)

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);
}

当先前的函数返回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]);

相关问题