JavaScript Sleep Function

  • Mike Duskis
  • Born
  • Born
  • No Avatar
  • Joined: Sep 30, 2008
  • Posts: 2
  • Status: Offline

Post October 10th, 2008, 12:25 pm

joebert,

I admit that sleeping in JavaScript is a kludgy thing to do, especially if we're talking about a Web application. Any time I consider sleeping, I usually come up with a more elegant solution.

I came across this discussion because I finally found a case where I really did want to sleep. I was developing a quick-and-dirty tool to evaluate the skills of software testers. It's a specialized calculator with all sorts of deliberate bugs. When interviewing candidates, I present them with this buggy calculator, give them a few minutes, observe their technique and tabulate how many defects they find. One of the defects is that the user interface becomes slow to respond under certain conditions. I use a sleep function to create this latency.
  • Anonymous
  • Bot
  • No Avatar
  • Joined: 25 Feb 2008
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post October 10th, 2008, 12:25 pm

  • PolishHurricane
  • Mastermind
  • Mastermind
  • User avatar
  • Joined: Feb 17, 2005
  • Posts: 1585
  • Status: Offline

Post October 11th, 2008, 11:35 pm

I have one that my AJAX class uses to wait for retry or something like that. This topic has a crazy hits, wow.
There's no place like 127.0.0.1, badass part is now it's ::1
  • lpickup
  • Born
  • Born
  • User avatar
  • Joined: Oct 31, 2008
  • Posts: 1
  • Loc: Raleigh, NC
  • Status: Offline

Post October 31st, 2008, 8:17 am

joebert wrote:
I still can't figure out what use a sleep function for JS is. :scratchhead:


Okay, here is why I need it: I am programming a multi-player game based on the old "concentration" game where you flip over two cards and if they match, you get a point. Otherwise play moves to the next player.

Now this work's great when you're playing it on a table and you see what cards the other player flipped, but when you're playing online and are at a different computer, I want to reveal the two cards that were flipped to the remote players, and I think it is more pleasing (and realistic) to flip one card over, wait a second, then flip the second one.

Okay, sure, I can certainly work around this with timeouts, etc. But really all I want is a simple sleep function so I can do this:

Code: [ Select ]
revealCard (card1);
sleep (1000);
revealCard (card2);
sleep (1000);
clearCards ();
 
// I would prefer to get control back here after cards are cleared.
  1. revealCard (card1);
  2. sleep (1000);
  3. revealCard (card2);
  4. sleep (1000);
  5. clearCards ();
  6.  
  7. // I would prefer to get control back here after cards are cleared.


Instead, my solution is:

Code: [ Select ]
revealCard (card1);
setTimeout("revealCard ("+card2+")", 1000);
setTimeout("clearCards()", 2000);
setTimeout("restOfCode("+var1+","+var2+",...,"+varN+")", 3000);
  1. revealCard (card1);
  2. setTimeout("revealCard ("+card2+")", 1000);
  3. setTimeout("clearCards()", 2000);
  4. setTimeout("restOfCode("+var1+","+var2+",...,"+varN+")", 3000);


where restOfCode is the code I want to execute after clearing cards, and var1-varN are the local variables I now want to pass to this code.

We can debate which is more elegant, but I personally think the sleep version is more straightforward.

...Lance
  • dings
  • Born
  • Born
  • No Avatar
  • Joined: Feb 24, 2009
  • Posts: 2
  • Status: Offline

Post February 24th, 2009, 7:37 am

I think this can be solved with the setTimeout function. At least in the
case where one wants to delay in a loop. If one creates a while-loop
between two functions the timeout can be used in one end.

Code: [ Select ]
 
function do_something(i) {
   if (i > 30)
     return;
   // do soemthing
   setTimeout("loop_implementation("+i+")", 10000);
}
 
function loop_implementation(i) {
   i = i + 1;
   do_something(i);
}
 
  1.  
  2. function do_something(i) {
  3.    if (i > 30)
  4.      return;
  5.    // do soemthing
  6.    setTimeout("loop_implementation("+i+")", 10000);
  7. }
  8.  
  9. function loop_implementation(i) {
  10.    i = i + 1;
  11.    do_something(i);
  12. }
  13.  


This way one can call do_something with 0 and it will be done 30
times with a 10 sec. delay between the steps. For an infinite loop
just replace return with setting i = 0.

--
Øyle
  • dings
  • Born
  • Born
  • No Avatar
  • Joined: Feb 24, 2009
  • Posts: 2
  • Status: Offline

Post February 24th, 2009, 7:51 am

General case.

Code: [ Select ]
 
function do_something(i) {
   switch(i) {
     case 0:
       before_wait();
       break;    
     case 1:
       after_wait();
       break;
     default:
       return;
   }
   setTimeout("loop_implementation("+i+")", 10000);
}
 
function loop_implementation(i) {
   i = i + 1;
   do_something(i);
}
 
function before_wait() {/* something */}
function after_wait() {/* something else */}
 
  1.  
  2. function do_something(i) {
  3.    switch(i) {
  4.      case 0:
  5.        before_wait();
  6.        break;    
  7.      case 1:
  8.        after_wait();
  9.        break;
  10.      default:
  11.        return;
  12.    }
  13.    setTimeout("loop_implementation("+i+")", 10000);
  14. }
  15.  
  16. function loop_implementation(i) {
  17.    i = i + 1;
  18.    do_something(i);
  19. }
  20.  
  21. function before_wait() {/* something */}
  22. function after_wait() {/* something else */}
  23.  


--
Øyle
  • dreaken667
  • Born
  • Born
  • No Avatar
  • Joined: Nov 20, 2009
  • Posts: 2
  • Status: Offline

Post November 20th, 2009, 3:03 pm

Just wanted to add my $0.02 to this:

Under any normal circumstances, there is no need for a real sleep function. As many others have indicated, there are more elegant solutions for most cases. In my case, I needed a real sleep function. I have an onUnload function that needs an extra second or two to process before the window is destroyed. In this case, setTimeout, and many other solutions failed and I needed a method to force the window to stay open and let the onUnload function do its business. It's a quick and dirty solution, but it sure beats rewriting someone else's code entirely.
  • joebert
  • Sledgehammer
  • Genius
  • No Avatar
  • Joined: Feb 10, 2004
  • Posts: 13458
  • Loc: Florida
  • Status: Offline

Post November 20th, 2009, 10:05 pm

All of you guys who want to use a sleep function to clog up script execution really should study event handlers better. Javascript has an awesome event model just for situations like these.

Explainit it in detail is beyond the scope of a single forum thread, but some useful search terms to include with your "javascript" queries will be "event handlers", "watch/unwatch", "callback functions", "addEventListener", "dispatch".

You're clogging up execution with while loops and jury rigged sleep functions like that. There are already timer loops running that look for events to perform actions for.

But hey, if it works for you, do it I suppose. :)
Strong with this one, the sudo is.
  • hidaet14
  • Born
  • Born
  • No Avatar
  • Joined: Aug 05, 2010
  • Posts: 1
  • Status: Offline

Post August 5th, 2010, 2:57 am

I have a problem, I have to postpone a function that sends an AJAX request in case the click of a button, for few seconds! So do not be the same function called twice!
Has anyone had a similar problem and solved it?
  • dreaken667
  • Born
  • Born
  • No Avatar
  • Joined: Nov 20, 2009
  • Posts: 2
  • Status: Offline

Post August 5th, 2010, 5:16 am

hidaet14, maybe you can resolve your issue with something similar to this?

Code: [ Select ]
running=false;
function onlyone(){
 if(running){return;}
 running=true;
 // function code here
 running=false;
}
  1. running=false;
  2. function onlyone(){
  3.  if(running){return;}
  4.  running=true;
  5.  // function code here
  6.  running=false;
  7. }
  • rugyoga
  • Born
  • Born
  • No Avatar
  • Joined: Oct 18, 2010
  • Posts: 1
  • Status: Offline

Post October 18th, 2010, 5:08 pm

A lot of times I thought I needed sleep, I found this did the job:

JAVASCRIPT Code: [ Select ]
function waitForCondition( interval, condition, action )
{
  if (condition())
    action();
  else
    setTimeout( 'waitForCondition( ' + interval + ', ' + condition + ', ' + action + ')', interval );
}
 
  1. function waitForCondition( interval, condition, action )
  2. {
  3.   if (condition())
  4.     action();
  5.   else
  6.     setTimeout( 'waitForCondition( ' + interval + ', ' + condition + ', ' + action + ')', interval );
  7. }
  8.  
  • mmainguy
  • Born
  • Born
  • No Avatar
  • Joined: Aug 08, 2011
  • Posts: 1
  • Status: Offline

Post August 8th, 2011, 7:11 am

Simplest solution that works and doesn't chew up CPU.
Code: [ Select ]
alert('start');
 //lots of code
 var a = 'foo';
 setTimeout(function(){
  alert(a);
  //lots more code
 },5000);
  1. alert('start');
  2.  //lots of code
  3.  var a = 'foo';
  4.  setTimeout(function(){
  5.   alert(a);
  6.   //lots more code
  7.  },5000);

Post Information

  • Total Posts in this topic: 26 posts
  • Users browsing this forum: No registered users and 159 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 2011 Unmelted, LLC. Ozzu® is a registered trademark of Unmelted, LLC.