【发布时间】:2016-11-26 20:24:39
【问题描述】:
我已经编写了这个函数,它使用 javascript 在网页上模拟交通信号。使用设置间隔,它每 20 秒重复一次。现在我需要在发生事件时退出函数,更具体地说是服务器使用 socket.io 发送的消息。现在我知道我可以清除间隔,因此该功能不会再次重复,但它不会在那一刻停止,这正是我所需要的。可以这样做吗?
(function startlights(){
socket.on('emergency', function(msg){ // I need to exit //startLights function when 'emergency' event occurs
console.log("mayhem "+msg);
});
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);
【问题讨论】:
-
这是由于 setTimeout 调用而发生的。该函数将在给定超时时触发,因为即使您清除了 repeatLights 计时器,您也不会清除该超时。
-
谢谢。现在我明白它为什么会这样运行了。
标签: javascript html css node.js socket.io