我需要这个循环永远运行,while
循环,每隔十秒检查一次事物的状态。因此,for
循环不是真正解决方案的一部分 - 但我在此示例中使用for
循环以避免挂起浏览器。
如何使用外部while
循环构造此代码,并且每次循环迭代与每次调用waitx函数时的3秒延迟之间有5秒的延迟。
所需的输出是:
display loop counter
wait 5 seconds
display curr time
wait 3 seconds
display time diff
(loop) display next loop counter
etc.
//$('body').css('background','wheat'); //test if js is broken
function waitx(truck){
console.log(truck);
$('div').html(truck);
setTimeout(function(){
newnow = new Date().getTime();
var diff = newnow - truck;
console.log(diff);
$('div').html(diff); //unwanted - just shows what SHOULD happen below
return diff;
},3000);
}
for (var nn=1; nn<6; nn++){
console.log(nn);
setTimeout(function(){
now = new Date().getTime(); //1479575397219
bonk = waitx(now);
//$('div').html(bonk + " hello"); //how to get this to work?
},5000);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div></div>
&#13;
答案 0 :(得分:1)
听起来你正在寻找一次又一次自我调用的功能
(function waitx(i) {
console.log('loop counter : ' + i);
setTimeout(function() {
var now = new Date().getTime();
console.log('current time : ' + now);
setTimeout(function() {
var diff = new Date().getTime() - now;
console.log('time diff : ' + diff);
waitx(++i);
}, 3000)
},5000);
}(0));
&#13;
答案 1 :(得分:1)
/*
display loop counter
wait 5 seconds
display curr time
wait 3 seconds
display time diff
(loop) display next loop counter
etc.
*/
(function startLoop(counter) {
console.log(counter);
setTimeout(function wait5Seconds() {
console.log(Date.now());
setTimeout(function wait3Seconds() {
console.log(Date.now());
startLoop(++counter);
}, 3000);
}, 5000);
})(0);