简体   繁体   中英

How do i loop my timed sequence for my program in JavaScript

I have made a program that displays a traffic light, the colour is changed when a button is pressed. I don't know how to add a timed sequence to this, can anybody help? My task is to allow the sequence to continue without any user input on a timer.

This is my original program

<!DOCTYPE html> 
<html> 
<body>  
  <h1>Task 3</h1> 
  <p>Traffic Light</p> 
  <img id="light" src="./assets/red.jpg">
  <button type="button" onclick="changeLights()">Change</button>  
  <script> 
    var list = ["./assets/red.jpg","./assets/redamber.jpg", "./assets/green.jpg","./assets/amber.jpg" ];
    var index = 0;
    function changeLights() {
      index = index + 1;      
      if (index == list.length) 
        index = 0;      
      var image = document.getElementById('light');     
      image.src = list[index]; 
    } 
  </script>  
</body> 
</html>   

I looked at timing events and attempted to use the setTimeout() function but all this does is adds a delay after each time the button is pressed.

<!DOCTYPE html> 
<html> 
<body>  
  <h1>Task 3</h1> 
  <p>Traffic Light</p> 
  <img id="light" src="./assets/red.jpg">
  <button onclick="setTimeout(changeLights, 3000);">Try it</button>  
  <script> 
    var list = ["./assets/red.jpg","./assets/redamber.jpg", "./assets/green.jpg","./assets/amber.jpg" ];
    var index = 0;
    function changeLights() {
      index = index + 1;      
      if (index == list.length) 
        index = 0;      
      var image = document.getElementById('light');     
      image.src = list[index]; 
    } 
  </script>  
</body> 

I am new to JavaScript and i wouldn't know where to start so i appreciate the help.

My task is to allow the sequence to continue without any user input on a timer.

You need to use setInterval(func|code, delay)

remove this line

<button onclick="setTimeout(changeLights, 3000);">Try it</button>  

And add this in your scripts

setInterval(changeLights, 3000);

setInterval is used when ever you want to run a function infinitely after every n milliseconds.

你可以试试这个

<button onclick="setInterval(changeLights, 3000);">Try it</button>

也许您的意思是使用setInterval()函数而不是setTimeout()。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM