I need help understanding why the following piece of code returns an undefined object property:
var count = 0;
var intervals = {
collection : []
}
intervals.collection[0] = function () {
this.timer = setInterval(function(){
count++;
$("p").html(count);
}, 1000);
}();
if(typeof intervals.collection[0] === "undefined") {
$("span").html("undefined");
}
Working Example: http://jsfiddle.net/tvaQk/8/
Basically, I’d like to be able to keep a collection of setIntervals that I can reference later so I can loop through and clear. I was thinking I’d be able to loop through the intervals.collection array and do something like:
clearInterval(intervals.collection[0].timer)
but cannot since intervals.collection[0] is undefined
You forgot the
return.Notice
thisrefers towindow, I’m not sure if adding a propertytimerto thewindowelement is what you were expecting actually. Otherwise, you shall return the interval id to not clutter the globalwindowscope.A short way to being able to access the
timerusingintervals.collection[0].timeris by creating an Object instead:I used
Array.pushin this example to add the newly created interval as the last element of the array.