1,105,633 Community Members

Is there a sleep/wait javascript function for firefox?

Member Avatar
Sailor_Jerry
Junior Poster in Training
88 posts since Aug 2005
Reputation Points: 3 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
-1
 

I need to suspend processing in my script for a few seconds, and i am not sure how.

Thanks, sj

Member Avatar
tgreer
Made Her Cry
1,885 posts since Dec 2004
Reputation Points: 189 [?]
Q&As Helped to Solve: 45 [?]
Skill Endorsements: 2 [?]
Team Colleague
 
0
 

There is no "sleep" or "wait" operator in JavaScript. You can set a timer, though, and when the timer expires, it will execute a function.

setTimeout("alert('hello')",1250);

You could have it wait so many milliseconds, and then execute an empty procedure, I suppose.

Member Avatar
alpha_foobar
Junior Poster
182 posts since May 2005
Reputation Points: 5 [?]
Q&As Helped to Solve: 5 [?]
Skill Endorsements: 0 [?]
 
1
 

What you usually do is what Tom has suggested, but you would invoke a call to the code that you want to execute after timeout.

So if you had an algorithm like such:

function myFunction(){
   doSomething();
   wait(500);
   doSomethingElse();
}

You would implement this with:

function myFunction(){
   doSomething();
   setTimeout(function(){doSomethingElse();}, 500);
}

This effective 'pauses' the execution of your code.

Member Avatar
Sailor_Jerry
Junior Poster in Training
88 posts since Aug 2005
Reputation Points: 3 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
0
 

Just what i needed.

Thanks guys, sj

Member Avatar
nemo5
Newbie Poster
6 posts since Dec 2006
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

This solution is not really a sleep. It effectively postpones the execution of function called by the setTimeout method, but javasctipy is asynchronous, so the execution of the commands following the setTimeout method will happend immediately after.
After a couple of google queries I found the only solution to sleep was to execute this function:

function pause(millis) 
{
        var date = new Date();
        var curDate = null;

        do { curDate = new Date(); } 
        while(curDate-date < millis)
}

Problem with this approach is when you need a few of shor sleeps one after another. In this case the only thing that happends is the cpu usage is gonna hit the roof and the script gets paused till the last pause is executed.

Member Avatar
Mark Whitt
Newbie Poster
2 posts since Jan 2006
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Thanks nemo5 for your input! I needed a way to cause a method to stop in its tracks so the calling method didn't think the currentl one was done yet, and this should do it.

Member Avatar
kanian77
Newbie Poster
1 post since Mar 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

The two approaches (do while, and dosomething/settimeout(dosomeelse)) are used in different situations.
1. do while
You just want to pause, but are not expecting anything to happen in the browser while waiting (no document loading, no event). The javascript interpreter will be busy executing the while loop.
(Check http://www.sean.co.uk/a/webdesign/javascriptdelay.shtm)
2. dosomething/settimeout(dosomeelse)
If you want your code to wait for something to happen, like a dom node being created or loaded you have to resort to other tactics.
Joseph Moore at http://40withegg.com/2007/1/5/a-non-cpu-intensive-javascript-wait-loop calls it a non-cpu intensive wait. Meaning the browser can still function and thus perform job that your code is waiting on.

Member Avatar
terrybleger
Newbie Poster
1 post since Nov 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

This code will freeze any threads after it's execution, so this is a useless one:

function jsWaitForDelay(delay) {
    var startTime = new Date();
    var endTime = null;
    do {
        endTime = new Date();
    } while ((endTime - startTime) < delay);
}

This codes will NOT freeze any threads after it's execution but only works for Firefox:

/**
 * Netscape compatible WaitForDelay function.
 * You can use it as an alternative to Thread.Sleep() in any major programming language
 * that support it while JavaScript it self doesn't have any built-in function to do such a thing.
 * parameters:
 *  (Number) delay in millisecond
*/
function nsWaitForDelay(delay) {
    /**
    * Just uncomment this code if you're building an extention for Firefox.
    * Since FF3, we'll have to ask for user permission to execute XPCOM objects.
    */
    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");

    // Get the current thread.
    var thread = Components.classes["@mozilla.org/thread-manager;1"].getService(Components.interfaces.nsIThreadManager).currentThread;

    // Create an inner property to be used later as a notifier.
    this.delayed = true;

    /* Call JavaScript setTimeout function
     * to execute this.delayed = false
     * after it finish.
    */
    setTimeout("this.delayed = false;", delay);

    /**
     * Keep looping until this.delayed = false
    */
    while (this.delayed) {
        /**
         * This code will not freeze your browser as it's documented in here:
         * https://developer.mozilla.org/en/Code_snippets/Threads#Waiting_for_a_background_task_to_complete
        */
        thread.processNextEvent(true);
    }
}
Member Avatar
tigerofdoom
Newbie Poster
3 posts since Mar 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I realize this is a pretty old thread, but it is easily found in Google.

Any approach that uses a while loop to wait is never going to be the best answer. We often refer to this technique as "spin wait" because it causes the cpu to keep crunching away at a process, sometimes stopping the entire machine (especially on older computers) meaning that your javascript wait could be intense enough for some users that their computing experience waits with you. This is not optimal.

While Javascript unfortunately does not provide a method of actually pausing the thread, setTimeout is your best bet. If there's any way that you can go to the trouble of implementing AlphaFoobar's method, then you 100% certainly should.

Member Avatar
jsreader
Newbie Poster
1 post since Oct 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
-1
 

Here is a website that has implemented a javascript sleep function in a few different ways. It also shows what methods are compatible with what browsers and operating systems.

http://www.devcheater.com

Member Avatar
Tornike k
Newbie Poster
1 post since Oct 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

If you create C++ component with one single function which internaly calls Win32 Sleep() function, then you can use this function from your java script and suspend thread. This way you can even implement WaitForSingleObject, SetEvent functions and synchronize threads, hope this should work.

Member Avatar
therealdeal1982
Newbie Poster
1 post since Nov 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I have researched a lot about this, nobody has a solution that does not use up cpu and works across browsers...
Here is my copyrighted method that really works... only downside is you have to chop up your code.

<html>
<body>
<script>
//javascript sleep by "therealdeal"; copyrighted 2009
//global var
var i = 0;
function start()
{
    dothese(i);
    i++;
    sleep(); //runs a timer to run start() again
    //if i==whatever, can use some other timer loop, etc...
    //if i>whatever, ends...
}

function dothese(pi) { //pi=passed i
    //pieces of codes to run
    if (pi==0){alert('0');}
    if (pi==1){alert('1');}
    if (pi==2){alert('2');} 
    if (pi > 2){alert(pi);}
}

function sleep() {t=setTimeout("start()",1000);} //can be a lot more than this
function sleep2() {t=setTimeout("start()",2000);} //alternate timer

start();
</script>
</body>
</html>
Member Avatar
kelek
Newbie Poster
1 post since May 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Here's all you'd have to do:

Suppose you're waiting for an ID field to exist. In the initial place you want to do it, add the line:

setTimeout("recursiveWait()", 250);

Then define the function:

function recursiveWait()
{
      if (document.getElementById("waitingId") == null)
      {
             setTimeout("recursiveWait()", 250);
      }
      else
      {
             <Do what you were waiting for here.>
      }
}

The stack could get large and overflow if your timer is too small (e.g., 1 ms and it really takes 10 seconds), but with some tuning it should work.

Member Avatar
old
Newbie Poster
4 posts since Feb 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I have researched a lot about this, nobody has a solution that does not use up cpu and works across browsers...
Here is my copyrighted method that really works... only downside is you have to chop up your code.

<html>
<body>
<script>
//javascript sleep by "therealdeal"; copyrighted 2009
//global var
var i = 0;
function start()
{
    dothese(i);
    i++;
    sleep(); //runs a timer to run start() again
    //if i==whatever, can use some other timer loop, etc...
    //if i>whatever, ends...
}

function dothese(pi) { //pi=passed i
    //pieces of codes to run
    if (pi==0){alert('0');}
    if (pi==1){alert('1');}
    if (pi==2){alert('2');} 
    if (pi > 2){alert(pi);}
}

function sleep() {t=setTimeout("start()",1000);} //can be a lot more than this
function sleep2() {t=setTimeout("start()",2000);} //alternate timer

start();
</script>
</body>
</html> 

end quote.

How is this copyrighted code? Variations of this code (if it works, I didn't check it) can be found in all applications that use Timeout and Interval.

Member Avatar
tgrendo
Newbie Poster
1 post since Oct 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Guys i need to do something similar to the above and i tried this

javascript:Code_1;wait(1000);Code_2;end();

Full code is the following

javascript:doc=document;if(window.frames.length>0)doc=window.main.document;url=document.URL;doc.forms[0].attack.click();wait(1000);doc=document;if(window.frames.length>0)doc=window.main.document;url=document.URL;doc.forms[0].submit.click();end();


But script executes the first part and then do nothing....
As error in console i get "wait is not defined"


Can someone correct this please?

Member Avatar
Taywin
Posting Maven
2,632 posts since Apr 2010
Reputation Points: 134 [?]
Q&As Helped to Solve: 378 [?]
Skill Endorsements: 17 [?]
 
0
 

Old thread... It's annoying to see old thread gets revived for nothing... Also, I usually use setTimeout() function to deal with sleep/wait anyway.

Member Avatar
akmr
Newbie Poster
1 post since Nov 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

try this:
when the window loads do the following:
var count=0
var int=setInterval('count++',0001)
then, when you want to wait:
var currenttime=count;
var stop_now=(currenttime+[how long to wait, in milliseconds])
while(count<=stopnow){}
this may cause an temporarily infinite loop, but should be okay.

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article