How to terminate endless while loop via setTimeout in Javascript

这一生的挚爱 提交于 2021-02-16 15:34:34

问题


I have a piece of code with while loop which I would like to stop by setTimeout(). But it seems like a endless loop, which never triggers setTimeout(). If I remove while loop, timeout triggers correctly. 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 );
});

回答1:


JavaScript runs a single event loop. 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.


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);
}



回答2:


As already mentioned the while loop blocks the one and only thread. To let your example do the thing you want, replace the while loop with setInterval(function) like this:

$(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);    
});



回答3:


setTimeout is never called do the the fact that the while never ends and so the even dispatcher is not going to trigger the setTimeout.



来源:https://stackoverflow.com/questions/40019974/how-to-terminate-endless-while-loop-via-settimeout-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!