1

I have two jfunctions in a page,

function function1(){
//codes
setTimeout("function1()",5000);
}

and

function function2(){
//codes
setTimeout("function2()",5000);
}

functions are called when

<div class="navPanel">
   <div onclick="function1();">Link1</div>
   <div onclick="function2();">Link2</div>
</div>

I need to stop working of function1 when function2 is called and viceversa....what to do.....??? help...

5
  • Why do you need that. Are you putting the functions on the same event? Commented Jan 31, 2013 at 11:04
  • When should the function starts working again once it is stopped? Commented Jan 31, 2013 at 11:04
  • No...in two different events... Commented Jan 31, 2013 at 11:05
  • Do you want to just stop the setTimeout() from firing? Commented Jan 31, 2013 at 11:07
  • @ATOzTOA...yes i want that.... Commented Jan 31, 2013 at 11:09

3 Answers 3

4

Set the timeouts to a variable which then allows you to use the clearTimeout function.

var timeout1 = {};
var timeout2 = {};

function function1(){
//codes
   if(timeout2){
      clearTimeout(timeout2);
   }
   timeout1 = setTimeout("function1()",5000);
}    

function function2(){
//codes
   if(timeout1){
       clearTimeout(timeout1);
   }
   timeout2 = setTimeout("function2()",5000);
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can do this, but not recommended...

function function1(){
    //codes
    setTimeout(function1,5000);

    function2 = function() {}
}

If you just want to stop the next execution of the setTimeout call, then just get a handle from setTimeout and call clearTimeout().

4 Comments

@melpomene "function1()" works same as function1 as long as you are not using clearTimeout().
You should not be passing strings to setTimeout() or setInterval().
@AnthonyGrist What if you want to call a function with arguments through setTimeout()?
Then you pass an anonymous function which calls it: setTimeout(function() { yourFunc(arg1, arg2, ...); }, 1000);.
1

Store the return values from the setTimeout() calls so that you can stop them with clearTimeout():

var function1Timeout,
    function2Timeout;

function function1(){
    //codes
    if(function2Timeout) clearTimeout(function2Timeout);
    function1Timeout = setTimeout(function1,5000);
}

function function2(){
    //codes
    if(function1Timeout) clearTimeout(function1Timeout);
    function2Timeout = setTimeout(function2,5000);
}

Note that I've changed your setTimeout() calls to pass function references, rather than strings.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.