我目前正在研究 RGB LED 灯条的控制器并写下效果,但我遇到了无法立即停止效果的问题。
我已经尝试了以下方法,但这并不能阻止效果。它仅在完成后停止效果。
function jump3() {
rgb.red = 255
rgb.green = 0
rgb.blue = 0
socket.emit("rgbLed", rgb)
var step1 = setTimeout(() => {
rgb.red = 0
rgb.green = 255
rgb.blue = 0
socket.emit("rgbLed", rgb)
}, 1000);
var step2 = setTimeout(() => {
rgb.red = 0
rgb.green = 0
rgb.blue = 255
socket.emit("rgbLed", rgb)
}, 2000);
}
我尝试过:
function jump3() {
if (stopEffect == 1) {
clearTimeout(step1)
clearTimeout(step2)
stopEffect = 0
return
}
rgb.red = 255
rgb.green = 0
rgb.blue = 0
socket.emit("rgbLed", rgb)
var step1 = setTimeout(() => {
rgb.red = 0
rgb.green = 255
rgb.blue = 0
socket.emit("rgbLed", rgb)
}, 1000);
var step2 = setTimeout(() => {
rgb.red = 0
rgb.green = 0
rgb.blue = 255
socket.emit("rgbLed", rgb)
}, 2000);
}
尝试将计时器变量的声明放在函数之外。
var stopAction = false;
var timer = false;
function action() {
if (stopAction) {
clearTimeout(timer);
stopAction = false;
return;
}
timer = setTimeout(function(){
let output = document.getElementById('output');
output.textContent = output.textContent + 'StackOverflow! ';
}, 1000);
}
document.getElementById('start').addEventListener('click', action);
document.getElementById('stop').addEventListener('click', function(){
stopAction = true;
action();
});
<div>
<button id="start">Start</button>
<button id="stop">Stop</button>
</div>
<div id="output"></div>