FacebookTwitterDiggDeliciousStumbleuponGoogle BookmarksRedditLinkedin

PHP has a sleep() function, but JavaScript doesn't. Well, this is because it's useless, you might say, and you'll be right. But for simulating heavy processing and for misc performance measurements, it could be useful. So here's how you can go about creating a sleep() in JavaScript.

The code

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

Usage

Sleep for 1 second (1000 milliseconds):

console.log(new Date());
console.log('Dude!');
sleep(1000);
console.log(new Date());

 

Read more about this in the original post from stoyanstefanov in phpied.com

Freedom Code

All existing content on this site can be used and modified to pleasure the developer who implements it. 

There are full and complete freedom to use the code. Developers can collaborate on this projects or recommend changes for improve it.

Contact