These are 4 buttons I have on my webpage below is the code:
<div id ="topbar" width="80%; height:20px;" style="text-align:center">
<input type="button" value="Click first" onclick="button.toggle();"></input>
<input type="button" value="Click second" onclick="button2.toggle();"></input>
<input type="button" value="Click third" onclick="button3.toggle();"></input>
<input type="button" value="Click fourth" onclick="button4.toggle();"></input>
</div>
Currently when page is loaded, all of them are “on” (toggle does On or Off)
How do I turn them all off, and then loop them like this:
1 on rest off
2 on rest off
3 on rest off
4 on rest off
1 on rest off…. and it keeps looping.
I have tried this approach
Whats wrong with this?
setInterval ( "loop()", 2000 );
function loop ( )
{
setTimeout ( "SetLayer1()", 1000 );
}
function SetLayer1()
{
button.toggle(); //all off since all of them are on from start
button2.toggle();
button3.toggle();
button4.toggle();
}
function SetLayer2()
button.toggle(); // button 1 on rest off
//button2.toggle();
//button3.toggle();
//button4.toggle();
}
function SetLayer3()
{
button.toggle(); // button 1 off
button2.toggle(); //button 2 on
//button3.toggle();
//button4.toggle();
}
function SetLayer4()
{
//button.toggle();
button2.toggle();// button 2 off
button3.toggle();// button 3 on
//button4.toggle();
}
That’s elementary, Watson. Recursion. An example implementation can be like this:
Make a variable holding all of your buttons and another variable called
index(or something like that.) Then, make a function.Inside that function, you do a check. If there is a
buttons[index](index is not larger or smaller than the length of all your button’s array), makeindex=0. Then, togglebuttons[index]and incrementindex.You then call
setTimeout– the first parameter being the name of the function, the second one being the amount of time you want to wait before firing it.Once outside of the function, call
setTimeoutin the same manner.Example: http://jsfiddle.net/bVNx2/