setInterval()只激发一次



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>

相关内容

  • 没有找到相关文章

最新更新