Unable to Clear Timeout - javascript

I have the following function that performs a setTimeout back on itself, i.e.:
var doIt = function(){
$('#comment_report').trigger('apexrefresh');
setTimeout("doIt()", 5000);
}
My question is, I am trying to clear the setTimeout that is looping through every 5 seconds, by issuing:
clearTimeout(doIt);
Unfortunately this didn’t work.
How would I go about clearing the above setTimeout?

You don't pass a string to clearTimeout(), you pass the Number which identifies the setTimeout() (which is returned by said function).
var timeoutId = null;
var doIt = function() {
$('#comment_report').trigger('apexrefresh');
timeoutId = setTimeout(doIt, 5000);
};
clearTimeout(timeoutId);
Alternatively, inside of doIt(), check for the condition and if it's met, then return only before you issue another call to setTimeout() (you won't have to keep track of the id that way).

var doit = function(){
};
var my_timeout_name = setTimeout( doit, 5000 );
clearTimeout( my_timeout_name );

setTimeout returns you an id that you can then pass to clearTimeout function.
Also, instead of this:
setTimeout("doIt()", 5000);
You can just pass a function:
setTimeout(doIt, 5000);

var myTimeout = false;
var doIt = function(){
$('#comment_report').trigger('apexrefresh');
myTimeout = setTimeout(doIt, 5000);
}
Then you should use
clearTimeout(myTimeout);

You are doing it wrong clearTimeout(timerid) this function takes the id of Timeout.
you can achieve this as
var mytimerid;
var doIt = function()
{
$('#comment_report').trigger('apexrefresh');
mytimerid = setTimeout("doIt()", 5000);
}
and then when ever required stop the timeout by
clearTimeout(mytimerid);

You need to assign a variable to the setTimeout that holds the id.
But in your code you seem to be assigning doIt to a function that does not return anything.
var timer;
timer = setTimeout("doIt()", 5000);
Then use
if(timer)
clearTimeout(timer);

Related

Why clearInterval doesn't work on a function

this is the code
var t = ()=>{
setInterval(()=>{
console.log('hello')
},1000)
}
t();
clearInterval(t)
Why the clearinterval does not block execution of the setInterval?
It doesn't work on a function because that's just now how the mechanism was designed. Calls to setInterval() return a number that acts as an identifier for the timer that the call establishes. That number is what has to be passed to clearInterval().
It doesn't cause an error to pass something that's not a number, or to pass a number that doesn't identify an active timer, but the call has no effect.
In your case, your t() function could simply return the result of the setInterval() call, and your outer code can save that for use later however you like.
It's because you need to return the id of the interval and clear that id.
According to the documentation:
setInterval returns an interval ID which uniquely identifies the
interval, so you can remove it later by calling clearInterval().
//function that keeps logging 'hello' on the console
var t = ()=>{
//return the id of the interval
return setInterval(()=>{
console.log('hello')
},1000)
}
//get the id of the interval created by the "t" function
var id = t();
//alerts the id just to see it
alert(id);
//clear it - function will stop executing
clearInterval(id);
References
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
because you should clearInterval on reference for setInterval().
var interval = setInterval();
clearInterval(interval);
T is not equal to the setInterval returned value as you don't return a value from your arrow function, and don't assign it to a value.
Try this snippet instead:
var t = ()=>
setInterval(()=>{
console.log('hello')
},1000)
var interval = t();
clearInterval(interval);
let intervalId = null;
cycle(true);
function cycle(r) {
let myInterval = () => {
return setInterval(() => plusSlides(1), 1000);
}
if (!r) {
clearInterval(intervalId);
} else {
intervalId = myInterval();
}
}

Javascript: setInterval isn't removed when nullifying an object

The setInterval function keeps running even though the object is nullified, should I change the setInterval var to null first or should I do something else? Also, will the GC remove the object even if the setInterval is still running?
Test = function(){
function start(){
// setTimout for controllable FPS
var loop = setInterval(function(){
console.log("TEST");
}, 1000);
}
start();
};
var test = new Test();
setTimeout(function(){
console.log("DIE!!");
test = null;
}, 2000);
JsFiddle
the value returned by setInterval is just a number that used to identify the reference to the interval. you can't just null it - you need to call window.clearInterval on the reference.
there's a few other things that don't make sense in the code you posted. for example, you're declaring a function in a function then just calling it once. i think this is probably closer to what you want:
var Test = function(){
this.start();
}
Test.prototype = {
loop : null,
start : function(){
this.loop = window.setInterval(function(){
console.log('TEST');
}, 1000);
},
stop : function(){
window.clearInterval(this.loop);
}
}
var test = new Test();
window.setTimeout(function(){
test.stop();
}, 5000);
That'll run the interval 5 times.
FWIW, the GC isn't really involved here. As long as there's a reference to any variable, it won't be collected.
HTH

Stopping Nested Timeouts in Javascript

I want to execute a piece of arbitrary code and be able to stop it whenever I want. I figured I could do this with setTimeout and then use clearTimeout to stop it. However if the code in the timeout creates it's own timeouts, then those keep executing even after I clear the original.
Example:
var timeoutID = setTimeout(
function(){
console.log("first event can be stopped with clearTimout(timeoutID)");
setTimeout(function(){console.log("but not this one")}, 5000)
}, 5000)
Now one way would be to control the code being executed and make it store the value of any additional timeouts into a global variable and clear them all at once. But is there a better way to do this? And is there a way to do this on arbitrary code?
To clarify, I'm trying to be able to execute any function I want, then stop it whenever I want, even if the function contains timeouts
You can put the inner timeout into a variable too:
var innerTimeout,
timeoutID = setTimeout(
function(){
console.log("first event can be stopped with clearTimout(timeoutID)");
innerTimeout = setTimeout(function(){console.log("but not this one")}, 5000);
}, 5000);
You would have to create an array of timeout IDs such as this:
var timeoutIds = [];
timeoutIds.push(setTimeout(
function(){
console.log("first event can be stopped with clearTimout(timeoutID)");
timeoutIds.push(setTimeout(function(){console.log("but not this one")}, 5000));
}, 5000))
And then to clear:
for (int i = 0; i < timeoutIds.length; i++)
{
clearTimeout(timeoutIds[i]);
}
timeoutIds = [];
You could wrap your timeouts in an object or re use timeoutID for the second timeout.
Wrap in an object:
function Timer(){
var me=this;
this.currentTimerID=setTimeout(function(){
console.log("First timeout");
me.currentTimerID=setTimeout(function(){
console.log("Second timeout");
},100);
},100);
};
Timer.prototype.cancel=function(){
clearTimeout(this.currentTimerID);
};
var t = new Timer();//let this run it's course
setTimeout(function(){t = new Timer()},250);//start timer again
setTimeout(function(){t.cancel();},400);// cancel it after the first timeout
Re use timeoutID:
var timeoutID = setTimeout(
function(){
console.log("first event can be stopped with clearTimout(timeoutID)");
timeoutID=setTimeout(function(){console.log("but not this one")}, 100)
}, 100)
setTimeout(function(){
clearTimeout(timeoutID);
},150);// will not execute the second timeout
One tip: If you're testing code with timeout then don't use such high values as it'll take 10 seconds for your original code to run.

Javascript setInterval function to clear itself?

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.
As long as you have scope to the saved interval variable, you can cancel it from anywhere.
In an "child" scope:
var myInterval = setInterval(function(){
clearInterval(myInterval);
},50);
In a "sibling" scope:
var myInterval = setInterval(function(){
foo();
},50);
var foo = function () {
clearInterval(myInterval);
};
You could even pass the interval if it would go out of scope:
var someScope = function () {
var myInterval = setInterval(function(){
foo(myInterval);
},50);
};
var foo = function (myInterval) {
clearInterval(myInterval);
};
clearInterval(myInterval);
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.
var myInterval = setInterval(function() {
if (/* condition here */){
clearInterval(myInterval);
}
}, 50);
see an EXAMPLE here.
var interval = setInterval(function() {
if (condition) clearInterval(interval); // here interval is undefined, but when we call this function it will be defined in this context
}, 50);
Or
var callback = function() { if (condition) clearInterval(interval); }; // here interval is undefined, but when we call this function it will be defined in this context
var interval = setInterval(callback, 50);
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:
var myFunction = function(){
if( stopCondition ) doSomeStuff(); //(do some stuff and don't run it again)
else setTimeout( myFunction, 50 );
}
myFunction(); //immediate first run
Simple as that :)
Of course if you REALLY want to use setInterval for some reason, #jbabey's answer seems to be the best one :)
You can do it by using a trick with window.setTimeout
var Interval = function () {
if (condition) {
//do Stuff
}
else {
window.setTimeout(Interval, 20);
};
};
window.setTimeout(Interval, 20);

Simple? question about how to clearInterval() in Javascript

My
setInterval('name(var)',6000);
won't clear with:
clearInterval('name(var)');
or with:
clearInterval('name(var)');
why?
setInterval returns a handle of the interval, so you do it like this:
var myInterval = setInterval(function(){ name(var) }, 6000);
clearInterval(myInterval);
Note: Notice how I used a anonymous function instead of a string too.
You need to store the returned intervalID and pass it to clearInterval later.
var intervalID = setInterval('name(var)',6000);
clearInterval(intervalID);
You need to pass in the interval id returned from setInterval
ex:
var id = setInterval('name(var)', 2000);
clearInterval(id);
More information here.
http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
This will work:
var id = setInterval('name(var)',6000);
clearInterval(id);

Categories