Javascript Timer To Switch Functions
I have three functions called toggle1(), toggle2(), toggle3() linked to my html. I want to make a timer to call each function with a delay of 5 seconds (5seconds for testing). I
Solution 1:
First problem is your for
loop is wrong, changing it to this should get you started:
for (var i = 0; i < 3; i++) {
Also, the delay
variable in each switch statement is redundant. Try changing the for loop first, that should start you off in the write direction.
Solution 2:
You have two basic syntactical problem which can cause issue
1) Syntax of for loop doesn't separated by ,
there should be ;
.
2) And there should be i<=3
. You have i=3
which will always be true.
for (i; i=3;i++){...}
Solution 3:
Try using the setInterval function.
var counter = 0;
functionToogle1() {
console.log("1");
}
functionToogle2() {
console.log("2");
}
functionToogle3() {
console.log("3");
}
functionTimeMachine() {
switch (counter) {
case0:
Toogle1();
counter++;
break;
case1:
Toogle2();
counter++;
break;
default:
Toogle3();
counter = 0;
break;
}
}
setInterval("TimeMachine()", 1000);
Solution 4:
functioninit () {
timer(1);
}
functiontimer(n) {
var delay = 5000;
switch (n) {
case1:
toggle1();
setTimeout(function(){ timer(2); }, delay)
break;
case2:
toggle2();
setTimeout(function(){ timer(3); }, delay)
break;
case3:
toggle3();
break;
}
}
Solution 5:
delayedExec([toggle1, toggle2, toggle3], 5000);
function delayedExec(fns, delay, index) {
index = index || 0;
if (index === fns.length) return;
fns[index]();
setTimeout(delayedExec.bind(null, fns, delay, ++index), delay);
}
Post a Comment for "Javascript Timer To Switch Functions"