Friday 4 July 2014

sleep() in JavaScript

FF Post : - 26

sleep()

     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.

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):
sleep(1000);

No comments:

Post a Comment