在JavaScript中的事件之后出来一个函数

时间:2016-11-26 20:24:39

标签: javascript html css node.js socket.io

我已经编写了这个函数,它使用javascript模拟网页上的交通信号。使用设定间隔,它每20秒重复一次。现在我需要退出函数,当有一个事件更具体地说是服务器使用socket.io发送的消息。现在我知道我可以清除间隔,所以功能不再重复,但它不会在那个瞬间停止,这就是我需要的。有可能这样做吗?



@Before




1 个答案:

答案 0 :(得分:1)

只需存储setTimeout()的结果并在其上调用clearTimeout()即可。例如:

function startlights() {
  socket.on('emergency', function(msg) {
    for (var i = 0; i < timeouts.length; ++i)
      clearTimeout(timeouts[i]);
    clearInterval(repeatLights);
    console.log('mayhem  ' + msg);
  });

  var timeouts = [
    setTimeout(function() {
      r1.css("background-color", "black");
      g1.css("background-color","green");
      r4.css("background-color", "red");
      y4.css("background-color","black");
    }, 1000),

    setTimeout(function() {
      g1.css("background-color","black");
      y1.css("background-color","yellow");
    }, 5000),

    setTimeout(function() {
      r1.css("background-color", "red");
      y1.css("background-color","black");
      r2.css("background-color", "black");
      g2.css("background-color","green");
    }, 6000),

    setTimeout(function() {
      y2.css("background-color","yellow");
      g2.css("background-color","black");
    }, 10000),

    setTimeout(function() {
      y2.css("background-color","black");
      r2.css("background-color", "red");
      g3.css("background-color","green");
      r3.css("background-color", "black");
    }, 11000),

    setTimeout(function() {
      y3.css("background-color","yellow");
      g3.css("background-color", "black");
    }, 15000),

    setTimeout(function() {
      y3.css("background-color","black");
      r3.css("background-color", "red");
      g4.css("background-color","green");
      r4.css("background-color", "black");
    }, 16000),

    setTimeout(function() {
      y4.css("background-color","yellow");
      g4.css("background-color", "black");
    }, 20000)
  ];
}

var repeatLights = setInterval(startlights, 20000);

我还应该指出,您只想添加一个'emergency'事件处理程序一次 删除任何现有的'emergency'事件处理程序在startlights()的开头,否则每次调用'emergency'时,您都会不断添加新的startlights()事件处理程序。