shadowayex Posted July 4, 2009 Share Posted July 4, 2009 As I'm sure many people are aware, the lack of a sleep() function is a pain to some more complex JavaScript programs. I've been working on trying to make one, to no avail. I've tried many set ups, and it all stops responding at the same point, the while loop designed to pause the script itself. Here's two set ups that I have that I though for sure would work.Both functions look like sleep(time) where time is the length, in milliseconds, that the script should sleep.Set up 1: The simpler of the two function sleep(time) { //Create Date Object var dateObj = new Date(); //Get Current Time var current = dateObj.getTime(); //Add Sleep Time To Calculate Stopping Time var end = current + time; //The Ingenious /*---------------------------------- The Following Loop Continues To Loop Until Current Is Greater Than End, Updating Current Everytime. Meaning, It Should Stop When The Current Time Is Past The End Time. ----------------------------------*/ while(current <= end) { current = dateObj.getTime(); //continuously find current time } } Set up 2: A little more complex, but not much function sleep(time) { //Create Date Object var dateObj = new Date(); //Get Current Time var current = dateObj.getTime(); //Add Sleep Time To Calculate Stopping Time var end = current + time; //The Ingenious /*---------------------------------- The Following Loop Continues To Loop Until Current Is Equal Than End, Updating Current Everytime. When It Equals End, Stop Is Changed To True And The Loop Should End*/ var stop = false; while(stop != true) { current = dateObj.getTime(); if(current == end) { stop = true; } } } I'm not sure why I thought the second script would work is the first one didn't, but whatever. I think the reason it's locking is because the script is calling dateObj.getTime() so much. I'm not sure where to go from here. Anyone have any ideas? Link to comment Share on other sites More sharing options...
Ingolme Posted July 4, 2009 Share Posted July 4, 2009 If the browser detects that a loop is being repeated too many times it will ask the user if they want to stop the script.You can use setTimeout for the sleep function: setTimeout(function() { // The rest of the application},3000); If you want to actually stop all of the executing code including event detection and the rest it gets more complex. I found an article here explaining a way:http://hyperstruct.net/2008/5/17/synchrono...-basic-solution Link to comment Share on other sites More sharing options...
shadowayex Posted July 7, 2009 Author Share Posted July 7, 2009 Oh... sad face =( I thought it was going to be simpler than that. Thanks for the site though. It'll help =). Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.