Here is a tidy javascript function that I found on stack overflow to mimic PHP’s usleep function which has been useful when testing javascript.
Be warned though, this will lock up the CPU, as control is not handed back until the time elapses. This is only intended for testing, debugging purposes, not to be used in a live production code.
// Basic sleep function based on microseconds (ms). // DO NOT USE ON PUBLIC FACING WEBSITES. function sleep(ms) { var unixtime_ms = new Date().getTime(); while(new Date().getTime() < unixtime_ms + ms) {} }
This function works in microseconds. If you would prefer to work in seconds and in effect mimic PHP’s sleep function, you simply need to multiple by 1000.
// Basic sleep function based on seconds. // DO NOT USE ON PUBLIC FACING WEBSITES. function sleep(s) { var unixtime_ms = new Date().getTime(); while(new Date().getTime() < unixtime_ms + ( s*1000 ) ) {} }
I’d recommend against this. It will spike a CPU core to 100% while “sleeping”, which is the worst kind of sleep 🙂
I haven’t experienced that, but perhaps it depends how long you sleep for, or what browser you run it on? Either way, this is just a function to be used when testing/debugging. Its simple and worked ok for me.
It is a super tight loop that is will keep the CPU spinning, with no chance for JavaScript to yield the CPU to something else. If you run it for very short periods then you are just spiking a CPU for very short periods of time, perhaps short enough to not be noticed.
Trying sleeping for 100 seconds and watch CPU utilization during that time.
This is all true. If you want to sleep safely use setTimeout, if you don’t care, use the function above 🙂