Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/vim/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在特定的时间段内挂起javascript线程_Javascript_Jquery - Fatal编程技术网

在特定的时间段内挂起javascript线程

在特定的时间段内挂起javascript线程,javascript,jquery,Javascript,Jquery,如何停止javascript在特定时间段内执行? 使用setTimeout功能,我可以在延迟后执行语句块,但在等待期间,将执行setTimeout旁边的语句。我可以暂停这个同步执行吗 根据要求,我在for循环中具有setTimeout功能。但在等待时间内,循环正在执行 以下是示例代码: for(i = 0;i < n;i++){ setTimeout(function(){ // Accessing the loop variable i inside this f

如何停止javascript在特定时间段内执行? 使用
setTimeout
功能,我可以在延迟后执行语句块,但在等待期间,将执行
setTimeout
旁边的语句。我可以暂停这个同步执行吗

根据要求,我在for循环中具有
setTimeout
功能。但在等待时间内,循环正在执行

以下是示例代码:

for(i = 0;i < n;i++){
    setTimeout(function(){
        // Accessing the loop variable i inside this function
    },3000);
}
(i=0;i{ setTimeout(函数(){ //访问此函数中的循环变量i },3000); }

您可以使用闭包,以便使用正确的
i
值:

for(设i=0;i<5;i++){
让divId=document.getElementById(“withTimeout”);
(职能(一){
如果(i%2==0)设置超时(函数(){
divId.innerHTML+=i+“”;
}, 3000);
})(i) );
}
for(设i=0;i<5;i++){
让divId=document.getElementById(“withoutTimeout”);
如果(i%2==0){
divId.innerHTML+=i+“”;
}
}
超时
没有超时

据我所知,挂起线程的唯一方法是同步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

您需要使用一个闭包,而不是“暂停”当前线程,因为不清楚您试图做什么。你的问题仅仅是
i
的值不是你想要的吗?是否要暂停脚本其余部分的执行?你想让数字一个接一个地出现吗?如果你的问题是想暂停循环本身,那么这可能就是你想要的:我想让“withTimeOut”div中的数字一个接一个地延迟出现。我曾尝试使用while循环来创建延迟,但没有用。代码如下:var timeAfterDelay=new Date().getTime();而(new Date().getTime()