简体   繁体   English

如何通过Java中的setTimeout终止无尽的while循环

[英]How to terminate endless while loop via setTimeout in Javascript

I have a piece of code with while loop which I would like to stop by setTimeout(). 我有一段带有while循环的代码,我想通过setTimeout()停止。 But it seems like a endless loop, which never triggers setTimeout(). 但这似乎是一个永无止境的循环,它永远不会触发setTimeout()。 If I remove while loop, timeout triggers correctly. 如果我删除while循环,超时将正确触发。 What is wrong please? 请问出什么事了?

$(document).ready(function() 
{
    var i = 0, s = false;

    setTimeout( function()
    {
        s = true;
        console.log( "Timeuot!!!" );
        console.log( "s value is " + s );
    }, 1000 );

    while( s === false )
    {
        console.log( "this is while and s is " + s );
        i++;
    }

    console.log( "iterations: " + i );
});

JavaScript runs a single event loop. JavaScript运行单个事件循环。 It won't stop in the middle of a function to see if there are any events (such as clicks or timeouts) that would trigger a different function. 它不会停止在函数中间,以查看是否有任何事件(例如单击或超时)会触发另一个函数。

In short: It won't run the timed function until the while loop has finished. 简而言之:在while循环完成之前,它不会运行定时功能。


To do this sort of thing, you'd normally have an event driven iterator. 为此,通常需要一个事件驱动的迭代器。

 var i = 0, s = false; setTimeout(function() { s = true; console.log("Timeuot!!!"); console.log("s value is " + s); }, 1000); next(); function next() { if (s) { return done(); } console.log({ s, i }); i++; setTimeout(next, 0); } function done() { console.log("iterations: " + i); } 

As already mentioned the while loop blocks the one and only thread. 如前所述,while循环阻塞了唯一的一个线程。 To let your example do the thing you want, replace the while loop with setInterval(function) like this: 为了让您的示例做您想做的事情,用setInterval(function)替换while循环,如下所示:

$(document).ready(function() 
{
    var i = 0, s = false;

    setTimeout( function()
    {
        s = true;
        console.log( "Timeout!!!" );
        console.log( "s value is " + s );
    }, 1000 );


    var interval = setInterval(function() {
      console.log( "this is while and s is " + s );
      i++;      
      if (s) {
        clearInterval(interval);
        console.log("i is " + i)
      }
    }, 100);    
});

setTimeout不会被调用,因为while永远不会结束,因此偶数调度程序不会触发setTimeout。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM