0

I'm having some issues with a method that is dependent on data being set in localStorage. Code:

function myFunction() {
    if (localStorage.getItem("token") == null || localStorage.getItem("token") == undefined) {
        setTimeout(function () {
        myFunction();
        }, 200);
    };

    // do other stuff dependent on the token in localStorage
    // do stuff
    // do stuff

}

This should keep calling the method every 0.2s until the condition is not met (localStorage.getItem("token") is NOT null). But what it does is that it goes through the condition and then keeps going through the function, instead of running from the beginning. This yields the result that in some cases, when token is not yet in localStorage, that a lot of token is not defined errors pop up and the javascript stops running. My expected behaviour is that it keeps running the function from the beginning until condition is not met.

Am I misunderstanding something or going about this problem the wrong way?

djur1
  • 39
  • 7
  • set `return;` statement at bottom of `if` block. That's said, i'm not sure why you use a timeout here?! – A. Wolff Jan 08 '18 at 13:10

1 Answers1

3

You could do it like that :

function myFunction() {
    if (localStorage.getItem("token") == null || localStorage.getItem("token") == undefined) {
        setTimeout(function () {
            myFunction();
        }, 200);
        return;
    };

    // do other stuff dependent on the token in localStorage
    // do stuff
    // do stuff

}

In that way, the return statement stops the function after the setTimeout is called. But I suggest you to review your code, and maybe fire an event when the token is set, or, better, a callback/promise.

Serge K.
  • 5,303
  • 1
  • 20
  • 27
  • `But I suggest you to review your code, and maybe raise an event when the token is set, or, better, a callback/promise.` Ya, absolutely! – A. Wolff Jan 08 '18 at 13:11
  • Thanks for the answer. This solution works but as you say -- it's not optimal. I instead set `async: false` to the request that gets and sets the token, so I don't have to manually await it in other methods. – djur1 Jan 08 '18 at 13:57
  • @djur1 **EDITED** No, no, no ! This will block your UI until there is a response ! No, you should really considerate using a promise, you can see few examples [here](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). – Serge K. Jan 08 '18 at 13:59