Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While until localStorage.getItem is '1' - Javascript

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?

like image 798
Warmix Avatar asked Mar 05 '26 12:03

Warmix


1 Answers

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 completes, 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).

like image 50
T.J. Crowder Avatar answered Mar 08 '26 01:03

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!