如何停止javascript执行一些特定的时间段?使用setTimeout
函数,我能够在延迟后执行语句块,但在等待时间内,setTimeout
旁边的语句正在执行。我可以挂起这个同步执行吗?
根据要求,我在for循环中有setTimeout
函数。但是在等待期间,循环正在执行。
for(i = 0;i < n;i++){
setTimeout(function(){
// Accessing the loop variable i inside this function
},3000);
}
http://jsfiddle.net/KK2mq/2/您可以使用闭包,以便使用正确的i
值:
for (let i = 0; i < 5; i++) {
let divId = document.getElementById("withTimeout");
(function(i) {
if (i % 2 == 0) setTimeout(function() {
divId.innerHTML += i + " ";
}, 3000);
})(i);
}
for (let i = 0; i < 5; i++) {
let divId = document.getElementById("withoutTimeout");
if (i % 2 == 0) {
divId.innerHTML += i + " ";
}
}
<h3>with timeout</h3>
<div id="withTimeout"></div>
<h3>without timeout</h3>
<div id="withoutTimeout"></div>
这将导致两个输出显示相同的值。但是你希望这些数字一个接一个出现3秒吗?如果是,你可以这样做:
(function display(i, step, max) {
let divId = document.getElementById("withTimeout");
setTimeout(function() {
divId.innerHTML += i + " ";
i += step;
if (i <= max) display(i, step, max);
}, 3000);
})(0, 2, 4);
<div id="withTimeout"></div>
display
函数是递归的,在显示前一个数字后每3秒调用一次自己,只要i <= 4
。整个东西周围的(...)(0, 2, 4)
意味着立即调用该函数,参数为(0, 2, 4)
。
我所知道的唯一挂起线程的方法是同步ajax,即使是同步ajax也是不赞成的。使用jQuery,如下所示:
$.ajax("/quickOne?arg="+arg,{async:false,success:d=>result=d});
但是也许你可以像第一个答案那样用延迟启动新的分离线程。在ES6中,您可以使用看起来重要且保持上下文的协程。唯一的问题是主线程将在不等待任何东西的情况下提前运行,但是有延迟的计算将在不同的线程中并行进行。例子:
var bgthread=function*(){
console.log("Starting a computation with delays");
$.post("/serverside",response=>{
processResult(response);
bgthread.next();
});
setTimeout(function(){bgthread.next()},3000);
console.log("yielding 1");
yield;
console.log("yielding 2");
yield;
console.log("All computations done");
}()//links
bgthread.next();//start the coroutine in background