IngBond
IngBond

Reputation: 668

How to stop a function in another function

How i can stop a function in another function?

For example:

var	snow = function(){
  var interval = setInterval( function(){
    alert('letItSnow')
  }, 1000);
};
snow();

clearInterval(snow.interval) - exception

Upvotes: 0

Views: 700

Answers (4)

Manish Mishra
Manish Mishra

Reputation: 12375

In javascript, access scopes are limited via function declarations, so your locally declared variables won't be accessible outside, hence you must return it or set it to a global variable (variable available in parent scope)

you need to make a slight adjustment to your function, do it like this:

var snow = function(){
            return setInterval(function(){
                alert('letItSnow');
            }, 1000);

        };

   var interval = snow();
   //on some event -- clearInterval(interval)

you can also make the setTimeout and its returned id a property to the function which would be available on all of its instances i.e.

var snowClass = function(){
     this.init = function(msg){
        this.interval = setInterval(function(){alert(msg)},1000);
    }

}
var snowObj  = new snowClass();
snowObj.init('Let it snow');
//on some event -- clearInterval(snowObj.interval)

Upvotes: 2

Moishe Lipsker
Moishe Lipsker

Reputation: 3034

If I understand the question correctly, you want to stop the interval outside of the snow function.

You can declare the interval variable outside of the snow function in order to use it (to clear the interval) outside of the snow function.

var interval;
var snow = function(){
    interval = setInterval(
        function(){
            alert('letItSnow')
        },
        1000
    );
};
snow();
clearInterval(interval);

Upvotes: 1

godblessstrawberry
godblessstrawberry

Reputation: 5048

you referring to snow.interval which assumed to be property of snow object. but in your code interval is just local variable. instead you might want to define interval in the global scope so it will be accessible globally http://www.w3schools.com/js/js_scope.asp

var interval, snow = function(){
  interval = setInterval( function(){
    console.log('letItSnow')
  }, 1000);
};
snow();
clearInterval(interval);

Upvotes: 1

Ganesh Putta
Ganesh Putta

Reputation: 2671

try this in your code

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: 0

Related Questions