skip to Main Content

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

2

Answers


  1. 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);
    
    Login or Signup to reply.
  2. Are you calling your function in the interval like x() or x?

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

    The first will run once the second till you clear it

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search