neoDev neoDev - 6 months ago 18
Javascript Question

call clear interval function from another function without pass the interval variable

I need to clear an interval from another function

jsFiddle

window.onload = function(){

var interval = null;

interval = setInterval(function(){
myFunction();
}, 1000);

function stop(){
clearInterval(interval);
}

}


without pass the interval variable

stop();


But I cannot make it working: when I call
stop();
the interval continues...

How can I do?

Answer

There is an unexpected window.stop function which preexists yours.
That's another proof that global variables/functions are evil.

It might be this function which gets invoked instead of yours, depending on when the script is loaded.

Try to put your function in an object to protect namespaces:

It works in the StackOverflow fiddle:

var i = 0;

function myFunction() {
  i++;
  console.log(i);
}

var interval = null;

interval = setInterval(function() {
  myFunction();
}, 1000);

var myObject = {
  stop: function() {
    console.log("stopping");
    clearInterval(interval);
  }
};
<button onclick="myObject.stop();">stop</button>

In the faulty jsFiddle, you get things in iframes, meaning window element is not the same. That's why your function is not invoked. That gives you that kind of errors:

enter image description here

You can put your script in the html to get it working:

jsfiddle

Comments