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

27

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

(注意: 这只是与setTimeout()相反的逻辑,因为setTimeout()先等待一定时间,然后再执行该函数。)


请问您能否给出几行代码?我认为您正在寻找.delay(),但现在还不确定。 - Arthur Halma
好的,我想你需要在执行其他操作之前等待2秒钟。使用setTimeout()函数来执行其他操作,然后再执行你的函数;-) - Didier Ghys
似乎你想在返回调用函数前等待2秒钟。如果是这样,请在返回之前使用setTimeout()。 - Rohan
1
@Rohan setTimeout() 是异步的,超时时间将被设置并且代码将继续执行。2秒后,操作将被执行,但不会按照脚本其余部分的顺序执行。 - Madara's Ghost
8个回答

45

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

例如:

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

8
我认为你需要的是一种暂停代码执行直到超时的方法。许多业余程序员希望有这样的结构,但在JavaScript中它不存在。它不是必要的。在JavaScript中,setTimeoutsetInterval是完美的解决方案。
然而,JavaScript是一种强大的语言。您可以构建自己的结构来解决此问题。请参阅Neil Mix的博客文章。通过他的方法,您可以创建一个sleep函数,该函数可按以下方式使用(请注意,目前只有Firefox支持JavaScript 1.7):
function mainGeneratorFunction() {
    functionToRunFirst();
    yield sleep(2000);
    //rest of the code
}

然而,对于其他浏览器不要绝望。您可以使用一种称为“XHR睡眠”的技巧。在此方法中,您只需使用同步的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的sleep函数如下:

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

3

使用 setTimeout 是一种实现它的方式。

function run() {    
    // run this code

    setTimeout(afterTwoSeconds, 2000);    
}

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

// call run
run();

1

"等待2秒"是什么意思?你的意思是要阻塞函数返回2秒钟吗?

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

你只能使用setTimeout()函数。


1

在您填写一些内容后,这应该以0.5秒的计时器运行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
    }
}

1

以上的答案都没有问题,但另一种方法是:

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

1
你这样写有些不专业啊。既然你选择使用 jQuery,为什么不用.delay()呢? - Madara's Ghost
因为我不知道.delay(),谢谢!我也以为楼主提到了jQuery,但似乎我错了。 - Grim...
他确实给他的问题打了jquery标签。 - Madara's Ghost

0

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


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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接