简体   繁体   中英

JS setTimeout won't wait 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); 

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

You need to remove the brackets 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM