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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8133947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:49:44  来源:igfitidea点击:

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

javascriptjqueryjavascript-events

提问by Mellon

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?

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

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

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

回答by GregL

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

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

e.g.

例如

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

回答by Aadit M Shah

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 setTimeoutand setIntervalare perfect candidate solutions.

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

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

然而,JavaScript 是一种强大的语言。您可以构建自己的构造来解决此问题。看看 Neil Mix 的博客文章。使用他的方法,您可以创建一个睡眠函数,该函数可以按照以下方式使用(请注意,目前只有 Firefox 支持 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 XMLHttpRequestto 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:

但是,对于其他浏览器不要绝望。您可以使用称为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

The php sleep function is as follows:

php睡眠功能如下:

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

回答by Russ Cam

using setTimeoutis one way to do it

使用setTimeout是一种方法

function run() {    
    // run this code

    setTimeout(afterTwoSeconds, 2000);    
}

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

// call run
run();

回答by Grim...

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

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

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

回答by Kae Verens

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

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

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

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

you'll have to just use setTimeout()

你只需要使用 setTimeout()

回答by NachoDawg

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

考虑到您的一些填写,这应该以半秒计时器运行 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
    }
}

回答by Siva

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.

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