最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

While until localStorage.getItem is '1' - Javascript - Stack Overflow

programmeradmin1浏览0评论

I have this code:

    localStorage.setItem('try', '1');
    setTimeout(function(){localStorage.setItem('try', '2');}, 2000);


    while(localStorage.getItem('try') == '1')
    {
        console.log('a');
    }

Why it's not working? This while loop should work until localStorage.getItem('try') == '1'. After 2 sec localStorage.setItem('try', '2') so this while should stop but doesn't do it :( Why? What should i use to make it work?

I have this code:

    localStorage.setItem('try', '1');
    setTimeout(function(){localStorage.setItem('try', '2');}, 2000);


    while(localStorage.getItem('try') == '1')
    {
        console.log('a');
    }

Why it's not working? This while loop should work until localStorage.getItem('try') == '1'. After 2 sec localStorage.setItem('try', '2') so this while should stop but doesn't do it :( Why? What should i use to make it work?

Share Improve this question asked Mar 26, 2017 at 16:03 WarmixWarmix 2278 silver badges16 bronze badges 1
  • 1 You're choking the execution engine hence the callback of your setTimeout never gets a chance to run because the event loop doesn't get its turn – haim770 Commented Mar 26, 2017 at 16:06
Add a ment  | 

1 Answer 1

Reset to default 7

Because the main JavaScript on your page is run in a single thread by the browser (along with the browser UI, on most of them), so your timed callback is sitting in the job queue waiting for the job that's currently running (the one with your while loop in it) to finish. Since your while loop job never pletes, the next job is never run.

Never busy-wait in browser-based JavaScript (it's rarely a good idea in any environment). Instead, schedule a callback via setTimeout to check on results after other jobs have been allowed to run, e.g.:

localStorage.setItem('try', '1');
setTimeout(function() {
    localStorage.setItem('try', '2');
}, 2000);

function check() {
    if (localStorage.getItem('try') != '1') {
        console.log('a');
    } else {
        setTimeout(check, 0);
    }
}

setTimeout(check, 0);

That's a very aggressive check, of course. You might use a much higher interval, perhaps 100 (10 times/second) or 250 (4 times/second).


Side note: I've used 0 as the callback time, which basically adds the timer callback to the job queue immediately (but after other jobs). The browser will respect that the first time, but when a timer callback schedules a timer, which schedules a timer, and so on, eventually the browser adds a minimum delay of 4ms (e.g., acting like you passed 4 instead of 0). The details on that are in the timers section of the HTML spec (which is about more than HTML).

发布评论

评论列表(0)

  1. 暂无评论