I'm trying to continuously loop through an array of number values which will be passed to a setInterval function as the delay value that triggers another function. Here is what I have:
HTML:
<p>On</p>
JavaScript:
$(document).ready(function(){
var timing = [5000, 10000, 17000, 8000, 14000, 9000, 12000, 8000, 20000, 7000, 13000, 7000, 17000, 8000, 13000, 12000, 18000]
//function to change
function change(){
var p = $("p").html();
if(p === "On"){
$("p").html("Off");
} else {
$("p").html("On");
}
}
function myFunction(){
for (var i = 0; i < timing.length; i++){
var switchTime = timing[i];
setInterval(function(){
change();
},switchTime);
}
} myFunction();
});
I'd like to have the change function fire continuously at different delayed times. Right now the timing doesn't seem to be correct when I run it. Any suggestions are appreciated. Thanks!
In any case, using a loop will not work, because a lot of setInterval
(or setTimeout()
) are "instantly" launched during a few microseconds.
So they do their job as stated by their own timing[i]
, but from almost the same time!
At the opposite, you must launch each step only when the previous one ends.
Here is a working example (see also this fiddle), where I added some visual tracking of the process:
HTML:
<p id="on-off">On</p>
<p id="delay"></p>
Javascript:
$(document).ready(function(){
var timing = [
5000, 10000, 17000, 8000, 14000, 9000, 12000, 8000, 20000, 7000, 13000,
7000, 17000, 8000, 13000, 12000, 18000
];
function myFunction(i){
i |= 0;
if (i < timing.length - 1) {
var switchTime = timing[i]
$onOff = $('#onOff');
$('#delay').html('i=' + i + ', delay=' + switchTime);
$onOff.html($onOff.html() == 'On' ? 'Off' : 'On');
setTimeout(
function() {
myFunction(i + 1);
}, switchTime
)
} else {
$('#delay').html('end');
}
}
myFunction();
});