[英]How to wait for a period of time after a function run
如果我有一个函数,我希望我的 js 代码立即运行它,但在运行后,等待 2 秒钟。 如何实现这个逻辑?
(注意:这只是与setTimeout()
比较的逆逻辑,因为setTimeout(
) 首先等待一定的时间然后执行该函数。)
只需将您的代码放在传递给 setTimeout 的匿名函数中。
例如
functionToRunFirst();
setTimeout(function() {
// rest of code here
}, 2000);
我认为您正在寻找的是一种暂停代码执行直到超时的方法。 许多业余程序员希望这样的结构,但它在 JavaScript 中不存在。 不需要。 对于 JavaScript 中的所有目的, setTimeout
和setInterval
都是完美的候选解决方案。
然而,JavaScript 是一种强大的语言。 您可以构建自己的构造来解决此问题。 看看 Neil Mix 的博客文章。 使用他的方法,您可以创建一个睡眠函数,该函数可以按照以下方式使用(请注意,目前只有 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"]);
?>
使用setTimeout
是一种方法
function run() {
// run this code
setTimeout(afterTwoSeconds, 2000);
}
function afterTwoSeconds() {
// run this code two seconds after executing run.
}
// call run
run();
考虑到您的一些填写,这应该以半秒计时器运行 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
}
}
“等待 2 秒”是什么意思? 你的意思是你想阻止函数返回 2 秒?
如果是这样,你不能那样做。 JavaScript 中没有 sleep() 函数。
你只需要使用 setTimeout()
上面的答案没有错,但另一种方式是:
$("#somethingThatDoesntExist").fadeTo(2000, 1, function() { // two seconds later });
我不知道你们为什么要走这么多。 我相信我们可以使用 Date 对象来做到这一点。 首先获取日期值并使用 setInterval 函数等待我们获得指定的时间间隔(获取新日期并检查差异)。 一旦我们得到重置间隔函数并在可以运行之后继续您的代码。
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]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.