I have a small problem.
The code is like this:
var myModule = (function() {
var _fun = function() {
console.log('dummy content');
};
var _init = function() {
_fun();
};
return {
init: _init,
}
})();
setInterval(myModule.init, 1000);
Is there any option to clearInterval() right after setInterval() and then start it once again ?
I would like to achieve something like this because each time I seInterval() I should clear it but unfortunately I don't know how to do this :/
Any suggestions ?
Simply assign setInterval return value to a variable and then use clearInterval on it, eg:
var myVar = setInterval(myModule.init, 1000);
clearInterval(myVar);
var myModule = (function() {
var _fun = function() {
console.log('dummy content');
};
var _init = function() {
_fun();
};
return {
init: _init,
}
})();
var interval = setInterval(myModule.init, 1000); // creates interval
clearInterval(interval); // clears the interval created above
When you set your interval keep a reference to it:
intervalObj = setInterval(yourCallbackFuction, INTERVAL_TIME);
Then clearing it:
clearInterval(intervalObj);
I'm using setIntervals within an each() function like so
$(".elements").each(function() {
setInterval(function() {
}, 1000);
});
Obviously a setIntervals is created for each element.
My question is: How do I clear all the setIntervals when I no longer need them? I have tried storing the setInterval in a variable and call window.clearInterval(int), but that only clears the last setInterval since each variable is overridden.
When you set an interval, you get a pointer to it:
var myInterval = setInterval(function(){}, 4000);
If you want to cancel an interval, you do the following:
clearInterval(myInterval);
So, for what you want to do, you would do the following:
var intervals = [];
$(".elements").each(function() {
var i = setInterval(function() {
}, 1000);
intervals.push(i);
});
Then if you need to cancel them all you can do this:
intervals.forEach(clearInterval);
That should do it for you.
There's no "clear-all-intervals" function.
You'll need to store all of them, and clear all of them:
var ints = [];
$(".elements").each(function() {
ints.push( setInterval(function() {
}, 1000)
);
});
// later
for ( var i = 0; i < ints.length; ++i )
clearInterval( ints[i] );
ints = []; // and forget them
This worked for me:
// clear interval
var id = window.setInterval(function() {}, 0);
while (id--) {
window.clearInterval(id);
var clearAllIntervals = function ( ) {
var intervals = [];
$(".elements").each(function() {
intervals.push( setInterval(function() {
}, 1000) );
});
return function clearAll ( ) {
intervals.forEach( clearInterval );
}
}( );
// When you want to clear them:
clearAllIntervals( );
If you are wanting to be compatible with IE8 or under you should shim .forEach, or replace it with a library equivalent, or a plain loop.
Since each interval is associated with an element, you could store the interval ID in the element:
$(".elements").each(function() {
$(this).data('interval-id', setInterval(function() {
// ...
}, 1000));
});
Then, if you want to clear the intervals,
$(".elements").each(function() {
clearInterval($(this).data('interval-id'));
});
I don't recommend you use this solution, but it really do the trick. The idea it to override setInterval function to collect all links to setInterval:
(function(originalSetInterval){
var intervals = [];
window.setInterval = function(func, timeout) {
var newInterval = originalSetInterval(func, timeout);
intervals.push(newInterval);
return newInterval;
}
window.clearAllIntervals = function() {
intervals.forEach(clearInterval);
}
})(window.setInterval)
To do a better job you would also need to override clearInterval to remove all intervals being clear already:
(function(originalSetInterval, originalClearInterval){
var intervals = [];
window.setInterval = function(func, timeout) {
var newInterval = originalSetInterval(func, timeout);
intervals.push(newInterval);
return newInterval;
}
window.clearInterval = function(interval) {
originalClearInterval(interval);
intervals.splice(intervals.indexOf(interval), 1)
}
window.clearAllIntervals = function() {
intervals.forEach(clearInterval);
}
})(window.setInterval, window.clearInterval)
When you set an interval, you get a pointer to it.
To clear all intervals, you'll need to store all of them:
var arr = [];
arr.push(setInterval(function () {
console.log(1);
}, 1000));
arr.push(setInterval(function () {
console.log(2);
}, 1000));
arr.push(setInterval(function () {
console.log(3);
}, 1000));
Following loop will clear all intervals
// Clear multiple Intervals
arr.map((a) => {
console.log(a)
clearInterval(a);
arr = [];
})
Interestingly, an interval handle ID is an incremental whole number greater than 0. So, all you'd have to do is create a no-function interval, and then for-loop it to clear all intervals from your latest interval handle ID down to 1.
let hInterval1 = window.setInterval(function(){console.log('interval A');},3000);
let hInterval2 = window.setInterval(function(){console.log('interval B');},3000);
for(let i = hInterval2; i > 0; i--) window.clearInterval(i);
If you run that sample, you'll see that we see 2 intervals running in the console emitting "interval A" and "interval B", and then by the time you run the for-loop, it stops both.
I am attempting to build a somewhat OOP jQuery plugin. Everything is going great, but I can't seem to get the start/pause function to implement correctly. I have the following 2 functions:
this.startAutoPlay = function() {
var interval = setInterval(function() {
obj.gotoNext();
}, config.timing);
};
this.stopAutoPlay = function() {
clearInterval(obj.startAutoPlay);
};
I just need a way to access the interval variable from within the stopAutoPlay function.
Any pointers?
You need to clear the interval that you set.
this.interval;
this.startAutoPlay = function() {
obj.interval = setInterval(function() {
obj.gotoNext();
}, config.timing);
};
this.stopAutoPlay = function() {
clearInterval(obj.interval);
};
I am having a hard time getting a countdown timer working as I don't know what I am doing wrong. I am trying to setup a countdown timer using jQuery in a prototype.
The main problem I see so far is at the setInterval:
_self.counter = setInterval(_self.runTimer(_self),1000);
When I don't pass in the "this" I get NaN but when I do the countdown only happens once and then stops.
Here is my JSFiddle work so far:
http://jsfiddle.net/f9GN7/
Thank you in advance.
I've modified a little of your code, I changed setInterval to setTimeout.
var timer_code = function(){
this.counter;
this.timeCountDown = 30;
}
timer_code.prototype = {
init : function(){
var _self = this;
$('#start').on('click',function(e){
_self.setTimer();
});
},
setTimer : function(){
var _self = this;
// _self.counter = setInterval(_self.runTimer(_self),1000);
var timerLoop = function(){
if(_self.timeCountDown > 0){
_self.runTimer();
setTimeout(timerLoop, 1000);
}
};
timerLoop();
},
runTimer : function(){
var _self = this;
_self.timeCountDown--;
if(_self.timeCountDown <= 0){
// clearInterval(_self.counter);
$('#timer').html("DONE");
return;
}
$('#timer').html(_self.timeCountDown);
console.log(_self.timeCountDown);
}
}
var timer = new timer_code();
timer.init();
http://jsfiddle.net/f9GN7/1/
setInterval gets a function reference as its first parameter ..
This function may not return a function object, the function call you just passed needs to be called in the scoope of a closure
Keeping your code with just a few modifications :
setTimer: function(){
if(this.counter)
clearInterval(this.counter); // timer may have already been launched, it may need to be cleared if its value is an integer and is != 0
this.counter = setInterval(
(function (ref) {
return function () {
ref.runTimer();
}
})(this),
1000);
}
See Fiddle Here
I have the following HTML page:
<html>
<script>
var global = {};
global.obj = {
// when called this function will cause 'hello' to be output to the
// console every 1 second
repeat: function () {
setInterval(function () {
console.log('hello');
}, 1000);
}
}
global.obj.repeat();
global.obj = [];
// even after we overwrite global.obj, 'hello'
// continues to be output to the console every second
</script>
</html>
I want to write a function similar to repeat, except when global.obj is overwritten, setInterval will stop being called
You'll want to use getters/setters, Mozilla has some good docs on this.
You may have to tweak it a bit:
var intervalRef = null;
var global = {objRef: {}};
global.__defineSetter__("obj", function(o) {
if (intervalRef)
clearInterval(intervalRef);
intervalRef = null;
global.objRef = o;
});
global.__defineGetter__("obj", function() {
return global.objRef;
});
global.obj = {
repeat: function () {
intervalRef = setInterval(function () {
console.log('hello');
}, 1000);
}
}
global.obj.repeat();
setTimeout(function() { //this just demonstrates that you can let it run for 5 secs before clearing the timer.
global.obj = [];
}, 5000);
I tested this and verified that it works.
See this Fiddle:
// html
<p id="stopper">Click</p>
// js
var counter = new Object();
counter.timer = setInterval( function(){
console.log("Hello!");
}, 1000 );
$("#stopper").click(function(){
console.log("Stopping");
clearInterval(counter.timer);
});