JS setTimeout won't wait for using Scratchpad

Consider the following script

function func()
{
  alert('b');
  if (document.readyState != 'complete')
    setTimeout(func(),1000);
  else
    alert('a');
};

window.location.replace('https://www.google.com/');
setTimeout(func(),5000);
      

Run codeHide result


When I run the script, I get an alert immediately without waiting 5 seconds.

+3


source to share


1 answer


You need to remove the parentheses from func:

 setTimeout(func,5000);

      

Otherwise, the function is called immediately, rather than being passed as a function to be called later.



function func()
{
  alert('b');
  if (document.readyState != 'complete')
    setTimeout(func,1000);
  else
    alert('a');
};

setTimeout(func,5000);
      

Run codeHide result


0


source







All Articles