javascript - Need a more efficient way to clear unresourceful setInterval() id's -
i in situation had create clear array of setinterval()
methods:
let intervals = [] for(let i=0; i<10; i++){ intervals.push( setinterval( function(){}, 1000 ) ) } for(let i=0; i<10; i++){ clearinterval( intervals[i] ) }
but whatever reason didn't work. came across this:
for (let i=1; i<9999; i++){ window.clearinterval(i) }
which worked perfectly, why should have use performance threatening hack clear bunch of intervals? noticed when logging interval id's this:
function makeintervals(){ let intervals = [] for(let i=0; i<10; i++){ intervals.push( setinterval( function(){}, 1000 ) ) } console.log( 'interval id\'s: ' + intervals ) for(let i=0; i<10; i++){ clearinterval( intervals[i] ) } } makeintervals() // interval id's: 5,6,7,8,9,10,11,12,13,14 makeintervals() // interval id's: 15,16,17,18,19,20,21,22,23,24 makeintervals() // interval id's: 25,26,27,28,29,30,31,32,33,34
you can see though old intervals cleared, new interval id's still being incremented , assigned each new setinterval()
.
is there reason creating new, incremented interval id's though previous id's cleared?
why not throw old id's pool instead of looping 9999+ times, have loop 10 times?
need more efficient way clear unresourceful setinterval() id's !
cheers.
edit: reason being such stickler because i'm using recursive function create new setinterval()
's , clear old ones. sooner or later 9999+ loops of clearinterval() wouldn't enough.
i think getting confused in thinking clearintervals(interval[i])
removing element i
intervals
array, not doing. once clear interval, there no reason store reference it, should remove array using array.splice
:
for (let = 0; < 10; i++){ clearinterval(intervals[i]); intervals.splice(i, 1); // remove element array }
now, when call function again, previous elements no longer exist in array start on @ 0.
also, instead of assuming array length 10, if want loop entire array should use array.length
:
for (let = 0; < intervals.length; i++){ clearinterval(intervals[i]); intervals.splice(i, 1); }
Comments
Post a Comment