How to Avoid Creating Multiple Intervals with JavaScript
When we wanat to create an app that is time controlled we may accidentally create multiple time intervals that can cause some problems. Consider this counter button.The more you click the faster it adds the counts. This is due to extra interval you create every time you click the button
<button onclick = "setInterval(()=>{this.innerHTML++},500)">0</button>
A simple solution is to clear the interval even before you create it.
<button onclick = "counting(this)">0</button>
<script>
var myInterval;
function counting(b){
clearInterval(myInterval);
myInterval = setInterval(()=>{b.innerHTML++},500)
}
</script>
Here my "myInterval" variable has to be set as a global variable otherwise, the interval won't be cleared.
<button onclick = "counting(this)">0</button>
<script>
function counting(b){
var myInterval;
clearInterval(myInterval);
myInterval = setInterval(()=>{b.innerHTML++},500)
}
</script>
A variable can contain one interval with an id.
If you create multiple intervals and assign them to a variable say "myVariable", then clear it with clearInterval(myVariable); It will only clear the last interval created.
- Click the "0" counter button once and then click the "Clear" button, the interval will be cleared.
- Click the "0" coutner more than once then click the "Clear", only the last created interval will be cleared.
This problem can be solved by clearing intervalas by their id, such as clearInterval(1);
Let take a look a look at interval id.
<script>
var interval = setInterval(()=>{console.log("hi")},500)
console.log(interval == 1);
// returns true
</script>
<script>
var interval = setInterval(()=>{console.log("hi")},500);
console.log(interval);
// return 1
interval = setInterval(()=>{console.log("hi")},500);
console.log(interval);
// return 2
interval = setInterval(()=>{console.log("hi")},500);
console.log(interval);
// return 3
</script>
Clear all 3 intervals
<script>
var interval = setInterval(()=>{console.log("hi")},500);
interval = setInterval(()=>{console.log("hi")},500);
interval = setInterval(()=>{console.log("hi")},500);
clearInterval(1);
clearInterval(2);
clearInterval(3);
</script>
One Solution is to Put Interval Ids in an Array.
<script>
var intervals = []
intervals.push(setInterval(()=>{console.log("hi")},500));
intervals.push(setInterval(()=>{console.log("hi")},500));
intervals.push(setInterval(()=>{console.log("hi")},500));
console.log(intervals);
// returns [1,2,3]
//Clear all Intervals
intervals.forEach(x=>{
clearInterval(x);
});
//Create other 3 intervals
intervals.push(setInterval(()=>{console.log("hi")},500));
intervals.push(setInterval(()=>{console.log("hi")},500));
intervals.push(setInterval(()=>{console.log("hi")},500));
console.log(intervals);
// returns [1,2,3,4,5,6]
</script>
Comments
Post a Comment