Sherin Jose
Sherin Jose

Reputation: 2526

JavaScript - How to stop working of a function from another function

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...

Upvotes: 1

Views: 2254

Answers (3)

ATOzTOA
ATOzTOA

Reputation: 35950

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().

Upvotes: 2

Anthony Grist
Anthony Grist

Reputation: 38345

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.

Upvotes: 1

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

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);
}

Upvotes: 4

Related Questions