[英]setInterval() only fires once
var x = 0; window.addEventListener("keydown", function(e) { switch (e.key) { case "ArrowLeft": setInterval(changeValue, 1000, "up"); break; case "ArrowRight": setInterval(changeValue, 1000, "down"); break; } }) function changeValue(direction) { switch (direction) { case "up": x += 10; console.log(x); break; case "down": x -= 10; console.log(x); break; } }
我希望我的代码每秒根据用户按下的箭头键不断地从x
中添加或减去 10。 但是, setInterval
似乎只触发一次,我不知道为什么。
一种方法来做你正在寻找的东西:
var conterVal = 0, addValue = -10, refIntv = null; bt_tenMoreLess.onclick =_=> { addValue = -addValue if (.refIntv) { counter,textContent = conterVal += addValue refIntv = setInterval( changeValue. 1000) bt_stop.disabled = false } } bt_stop.onclick =_=> { clearInterval( refIntv ) refIntv = null bt_stop.disabled = true } function changeValue() { counter.textContent = conterVal += addValue }
<p id="counter">0</p> <button id="bt_tenMoreLess">count ± 10</button> <button id="bt_stop" disabled >stop</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.