myInterval = setInterval(function(){
MyFunction();
},50);
function MyFunction()
{
//Can I call clearInterval(myInterval); in here?
}
The interval's not stopping (not being cleared), if what I've coded above is fine then it'll help me look elsewhere for what's causing the problem. Thanks.
EDIT: Let's assume it completes a few intervals before clearInterval is called which removes the need for setTimeout.
will do the trick to cancel the Interval whenever you need it. If you want to immediately cancel after the first call, you should take
setTimeout
instead. And sure you can call it in the Interval function itself.see an EXAMPLE here.
Or
You can do it by using a trick with window.setTimeout
As long as you have scope to the saved
interval
variable, you can cancel it from anywhere.In an "child" scope:
In a "sibling" scope:
You could even pass the interval if it would go out of scope:
From your code what seems you want to do is to run a function and run it again and again until some job is done...
That is actually a task for the
setTimeout()
, the approach is similar:Simple as that :)
Of course if you REALLY want to use setInterval for some reason, @jbabey's answer seems to be the best one :)