How to Make A Time Controlled Loop in JavaScript
For loops are used all the time in software development. But for loops do not have the time controlled mechanism. We have to build it from scratch.
Suppose we want to show elements in an array. Without time control effect, it will just print everything out at once.
<button onclick = "showNumberFunc()">Print</button>
<div id = "showNumbers"></div>
<script>
var arr = [1,2,3,4,5,6,7,8,9];
function showNumberFunc(){
showNumbers.innerHTML = "";
for(let i = 0;i < arr.length; i++){
showNumbers.innerHTML += arr[i];
};
};
</script>
<button onclick="showNumberFunc_timeControlled()">Print</button>
<div id="showNumbers_timeControlled"></div>
<script>
var arr = [1,2,3,4,5,6,7,8,9];
var i;
var myInterval;
function print(){
showNumbers_timeControlled.innerHTML += arr[i];
i++;
if(i == arr.length){
clearInterval(myInterval);
};
};
function showNumberFunc_timeControlled(){
i = 0;
clearInterval(myInterval);
showNumbers_timeControlled.innerHTML = "";
myInterval = setInterval(print,1000);
};
</script>
The Problem is Messy Code
When creating time controlled loop, we need to define some index variable and interval variable to store the interval. The problem is when creating too many time controlled loop, our code will become vary hard to manage. One solution is to create objects.
<button onclick="timeControlledObj.loop()">Print</button>
<div id="showNumbers_timeControlled_1"></div>
<script>
var timeControlledObj = {
data:[1,2,3,4,5,6,7,8,9],
i:0,
interval:0,
loop:function(){
clearInterval(this.interval);
showNumbers_timeControlled_1.innerHTML = "";
this.i = 0;
this.interval = setInterval(this.print.bind(this),500);
},
print:function(){
showNumbers_timeControlled_1.innerHTML += this.data[this.i];
this.i++;
if(this.i == this.data.length){
clearInterval(this.interval);
}
}
}
</script>
When do I Use Time Controlled Loop
I use the time control loop when I draw a graph with time effect.
Comments
Post a Comment