javascriptnode.jsweblocal-storage

Keep checking if a function returns true in local storage


I'm trying to check if a function returns true in an if/else statement, however I want to keep checking if the function returns true and when it does to execute the code...

How would I go about this? I have tried setInterval and setTimeout and it won't repeat, unless I'm missing something...

I have also tried a while loop but this is inefficient and crashes the browser...

However if I use an setInterval() how would I clear it once x returns true?

Here is a snippet of my code for an example.

function x() {
    if (localStorage.getItem("a") === null) {
        return false;
    } else {
        return true;
    }
}

if (!x()) {
    console.log("Returned True!");
    update();
} else {
    console.log("False");
}

Solution

  • setInterval() should work

    function x() {
        return localStorage.getItem("a") !== null;
    }
    
    let interval = setInterval(() => {
        if (x()) {
            console.log("Returned True!");
            update();
            clearInterval(interval);
        } else {
            console.log("False");
        }
    }, 500);