clearInterval()setInterval()启动停止不起作用

时间:2019-07-09 02:32:41

标签: javascript

我正在尝试启动一个功能,并在按下右箭头键时重复该功能,在按下左箭头键时停止,并在再次按下右箭头键时再次启动,等等。

按下左箭头键不仅不会停止功能,即使先按下左箭头键也会启动。

非常感谢您的帮助。

我什至在右箭头键函数中放置了clearInterval(),因为我认为它与多个实例有关,我读了另一篇文章,但对发生的事情不太清楚。

var repeater = null;

function beginInterval() {
    clearInterval(repeater);
    repeater = setInterval(myFunctionThatNeedsRepeating, 1000);
};

function endInterval() {
    clearInterval(repeater);
};

document.onkeydown = function(e) {
    switch (e.key) {
        case 'ArrowLeft':
            endInterval();
        case 'ArrowRight':
            beginInterval();
    }
};

当按下向右箭头键时,我要启动SetInterval()。 当我按下向左箭头键时,我希望SetInterval()停止。

该代码目前根本无法停止。

0 个答案:

没有答案
相关问题