In javascript when I create an interval, I want to stop the interval from inside the function, but I don't want to reference the ID value from outside like this
var y = setInterval(function(){ clearInterval(y); }, 1000);
What I want is to pass a variable similar to this style
setTimeout(function(data){alert(data);}, 1000, "data");
This works for setInterval too, except I can't really pass the id value that's returned by the setInterval function, because it gets created after calling it.
Right now I'm doing a hack like this:
var r = [];
var y = setInterval(function(r){ if (r.length==1) { clearInterval(r[0]); } }, 1000, r);
r.push(y);
Does anyone know the right way?
Thanks
You have to use the return value, but that doesn't mean that the variable needs to be accessible to anything else; just encapsulate:
y
in the above is only accessible within the outer anonymous function, which only has the interval function and nothing else in it.You could even give yourself a reusable
setInterval
wrapper to do it:That will pass the time handle as the first argument, in front of any others you specify. It also has the benefit of supporting those follow-on arguments reliably cross-browser (some older browsers didn't support passing arguments to the callback).
Gratuitous example:
You can create a new method, which can provide you the desired functionality, like
Now this works like
which prints
Hello
and Interval Id (same as myInterval)