如果我有一个函数,我希望我的js代码立即运行它,但在执行后等待2秒钟。如何实现这个逻辑?
(注意: 这只是与setTimeout()
相反的逻辑,因为setTimeout()
先等待一定时间,然后再执行该函数。)
如果我有一个函数,我希望我的js代码立即运行它,但在执行后等待2秒钟。如何实现这个逻辑?
(注意: 这只是与setTimeout()
相反的逻辑,因为setTimeout()
先等待一定时间,然后再执行该函数。)
只需将您的代码放入传递给setTimeout的匿名函数中即可。
例如:
functionToRunFirst();
setTimeout(function() {
// rest of code here
}, 2000);
setTimeout
和setInterval
是完美的解决方案。function mainGeneratorFunction() {
functionToRunFirst();
yield sleep(2000);
//rest of the code
}
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"]);
?>
使用 setTimeout
是一种实现它的方式。
function run() {
// run this code
setTimeout(afterTwoSeconds, 2000);
}
function afterTwoSeconds() {
// run this code two seconds after executing run.
}
// call run
run();
"等待2秒"是什么意思?你的意思是要阻塞函数返回2秒钟吗?
如果是的话,你不能这样做。在JavaScript中没有sleep()函数。
你只能使用setTimeout()函数。
在您填写一些内容后,这应该以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
}
}
以上的答案都没有问题,但另一种方法是:
$("#somethingThatDoesntExist").fadeTo(2000, 1, function() {
// two seconds later
});
.delay()
呢? - Madara's Ghost我不知道你们为什么要这么麻烦。我相信我们可以使用Date对象来完成它。首先获取日期值,然后使用setInterval函数等待指定的时间间隔(获取新的日期并检查差异)。一旦我们得到了它,重置interval函数,然后继续运行你的代码。
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);
}
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]);
setTimeout()
是异步的,超时时间将被设置并且代码将继续执行。2秒后,操作将被执行,但不会按照脚本其余部分的顺序执行。 - Madara's Ghost