1

I'm trying to wait for an API to load, however my test code below doesn't seem to be taking the timeout delay into account as it's looping too quickly.

var google = false;
  function test(check = false) {
    if (!check) {
      console.log('append the api');

      check = true;
    }
    if (check) {
      console.log('check api is loaded');
      if(!google){
        console.log('not loaded');
        setTimeout(test(true), 10000);
        return;
      } else {
        console.log('loaded');
      }
    }
  }

This code should just keep displaying the 2 console.log's until the google variable is changed to true.

I'm unable to change this though as the browser freezes up due to so many loops.

Martyn Ball
  • 4,679
  • 8
  • 56
  • 126

3 Answers3

2

You fault is in this line:

setTimeout(test(true), 10000);

You must pass the function and dont call it. If you want to pass parameters, do it like this:

setTimeout(function(){test(true)}, 10000);
1

As Jonas w said you should use setTimeout(test,1000,true) instead of setTimeout(test(true),1000), see the explanation below:

According to MDN WindowOrWorkerGlobalScope.setTimeout() you should pass three variables to setTimeout: function, timeout value and parameters which will be passed to invoked function. Functions in JavaScript are first class objects, so you pass them as regular object. In your example you don't actually pass a function but invoke it immediately and to setTimeout passed value which returned from this function.

Anatoly
  • 5,056
  • 9
  • 62
  • 136
-1

You are recursively invoking the test function immediately, because you are actually setting the timeout for the value returned by test, which is undefined.

You want to put test(true) in an anonymous function, like so:

var google = false;
function test(check = false) {
  if (!check) {
    console.log('append the api');
    check = true;
  }
  if (check) {
    console.log('check api is loaded');
    if(!google){
      console.log('not loaded');
      setTimeout(() => test(true), 10000);
      return;
    } else {
      console.log('loaded');
    }
  }
}

Note the arrow () => – this creates an anonymous function that is invoked when the timeout has elapsed. If you don't like using this newfangled arrow function stuff, you can also write:

var google = false;
function test(check = false) {
  if (!check) {
    console.log('append the api');
    check = true;
  }
  if (check) {
    console.log('check api is loaded');
    if(!google){
      console.log('not loaded');
      setTimeout(function () {
        test(true);
      }, 10000);
      return;
    } else {
      console.log('loaded');
    }
  }
}
Patrick Hund
  • 19,163
  • 11
  • 66
  • 95