0

My HTML has 5 images of lightOff.jpg bulbs + 1 button.

My mission is to press a button and then turn on the lights (change the images to lightOn.jpg) one by one every of 1 second. Meaning 1 bulb will on and after 1 second the next bulb will on and so on…. This is what I try to start….

function turnOnLights() {
  var bulb = ["one", "two", "three", "four"];
  for (var i = 0; i < bulb.length; i++) {
    setTimeout(function() {
      document.getElementById(bulb[i]).src = "https://maxcdn.icons8.com/app/uploads/2015/12/light_on-1.png"
    }, 1000);

  }
};
#containger {
  text-align: center;
  vertical-align: middle;
  line-height: 30px;
  margin-top: 20px;
}
<div id="containger">

  <img src="https://maxcdn.icons8.com/app/uploads/2015/12/light_off-1.png" id="one">
  <img src="https://maxcdn.icons8.com/app/uploads/2015/12/light_off-1.png" id="two">
  <img src="https://maxcdn.icons8.com/app/uploads/2015/12/light_off-1.png" id="three">
  <img src="https://maxcdn.icons8.com/app/uploads/2015/12/light_off-1.png" id="four">

  <br>

  <button type="button" onclick="turnOnLights();">Click to turn on lights</button>





</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
daniel
  • 1
  • 1
  • 1
    what is the issue? – Nagaraju Apr 25 '17 at 07:35
  • 2
    Also, you need to set the timeout to `1000*i`. Otherwise they all switch on after one second. – JJJ Apr 25 '17 at 07:37
  • I created a snippet for you with images to show you how to format your code into a [mcve] – mplungjan Apr 25 '17 at 07:44
  • The code you want is `for (var i = 0; i < bulb.length; i++) { (function(index){ setTimeout(function() { document.getElementById(bulb[index]).src = "lightOn.jpg" }, 1000*index); })(i);` – mplungjan Apr 25 '17 at 07:49

0 Answers0