Wednesday, November 11, 2009

Prototype JS - Sleep Function

Every once in a while, you need to simulate network latency in an
application when you are doing AJAX. It's a hard thing to test unless
you actually are talking to a remote server. Yes, you could do it with
a proxy server and it's something I've done, but it's cumbersome at

Here's a simple sleep() function written in prototype:

sleep: function(milliseconds) {
var start = new Date().getTime();

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

Basically, we are exploiting the ability to get the current system time
in milliseconds and comparing the current time in the loop against the
time in milliseconds when we started to get a difference. This function
is not appropriate if you want an action to occur is X number of
milliseconds because this function delays execution of code due to the
loop. Use a setInterval() or setTimeout() function that is part of
Javascript to "schedule" when a method should be executed.

1 comment:

  1. im new to prototype, how would i attach this to my method?