如何使我的停止按钮取消我的红绿灯序列?

时间:2016-11-19 17:17:32

标签: javascript html css

我创建了一个显示红绿灯的网站。当用户点击按钮时,指示灯会按顺序改变。只是想知道,有没有办法让#34;停止"按钮,当用户点击它时,序列在当前所在的图像上停止?

这是我的代码:

GetFilesAsync

2 个答案:

答案 0 :(得分:3)

clearInterval()将终止您的间隔计时器。尝试类似:

clearInterval(timer)

Explanation of clearInterval().

答案 1 :(得分:0)

正如大家所说,您可以使用clearInterval重置此功能。无论如何,我已经使用下面的clearTimeoutsetTimeout重构了您的代码,因为您没有有效地处理每个灯光的持续时间。

<!DOCTYPE html>
<html>
<body>

<h1><u> Traffic Light Sequence </u></h1>

<p>Press the button to begin.</p>

<img id="colour" style="width: 100px; height: 100px;">


<button type="button" onclick="changeLights()">Change Lights</button>
<button type="button" onclick="resetLights()">Reset Lights</button>

<script>
  var lightIndex = -1;
  var timer;
  var trafficLight = document.getElementById('colour');
  var lights = [{
    duration: 10,  // seconds
    image: 'https://upload.wikimedia.org/wikipedia/commons/thumb/1/1f/Red_Light_Icon.svg/232px-Red_Light_Icon.svg.png'
  }, {
    duration: 3,  // seconds
    image: 'http://www.caloritherm.hu/assets/images/light-yellow-flash.gif'
  }, {
    duration: 6,  // seconds
    image: 'http://www.clipartkid.com/images/511/green-light-clip-art-l-clip-art-category-clipart-w3ET7s-clipart.png'
  }, {
    duration: 3,  // seconds
    image: 'https://upload.wikimedia.org/wikipedia/commons/thumb/4/45/Yellow_Light_Icon.svg/1024px-Yellow_Light_Icon.svg.png'
  }];

  function resetLights() {
    lightIndex = -1;
    //clearInterval(timer); 
    if(timer) {
      clearTimeout(timer);
      timer = null;
    }
  }

  function changeLights() {  
    if(++lightIndex === lights.length) {
        lightIndex = 0;
    }
       
    trafficLight.src = lights[lightIndex].image;
    timer = setTimeout(changeLights, lights[lightIndex].duration * 1000);
  }
  
  changeLights();
</script>

</body>
</html>