Php Sleep function in javascript

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 ) ) {}
}

Kudos to Ian Maddox

4 thoughts on “Php Sleep function in javascript

    1. 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.

      1. 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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s