gpt4 book ai didi

javascript - 如何立即停止设置为间隔的函数

转载 作者:行者123 更新时间:2023-12-02 23:33:57 24 4
gpt4 key购买 nike

我目前正在开发 RGB LED 灯带的 Controller 并编写效果,但我遇到了无法立即停止效果的问题。

我已经尝试过以下方法,但这并不能阻止效果。它只会在完成后停止效果。

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>

关于javascript - 如何立即停止设置为间隔的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56365144/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com