【问题标题】:setInterval not working when declared as globalsetInterval 在声明为全局时不起作用
【发布时间】:2016-11-06 15:46:36
【问题描述】:

我有 3 个全局声明的 setInterval 函数,其中 2 个正在工作,另一个不管我做什么都不起作用。我正在使用一个单独的函数来清除间隔(函数 ClearintervalTime()),它在 stopGame() 中调用

var clearIntervalvariable0, clearIntervalvariable1, clearGameInterval1=null;

function gameDuration() {
    counter = 90;
    clearGameInterval1 = setInterval(gameDurationCounter, 1000);

    function gameDurationCounter() {
        counter--;
        document.getElementById('timer').innerText = 'Time remaining:' + counter;
        speed();
        if (counter == 0) {
            stopGame();
            // clearInterval(clearGameInterval1);
            console.log('game was stopped');
        };
    };
};

function ClearintervalTime() {
    clearInterval(clearGameInterval1);
    clearInterval(clearIntervalvariable0);
    clearInterval(clearIntervalvariable1);

};
function stopGame() {
    bubbles.length = 0;
    noLoop();
    ClearintervalTime();
};

无论我做什么,这段代码都不起作用,唯一让它起作用的是,如果我在 gameDuration() 本地声明 clearGameInterval1 ,然后在闭包函数 gameDurationCounter() 中用注释行关闭它。 我有一个停止游戏按钮,我不仅要在计数器达到 0 时关闭间隔,还要在按钮点击时关闭。 如果我保留上面列出的代码,如果我注释掉 clearInterval(clearGameInterval1);在 ClearintervalTime() 中,计数器将启动,但我无法停止/清除它……我想解决这个问题。没有其他同名的变量或函数,我试图让 gameDurationCounter() 外部(不是在闭包中)相同的效果。谁能告诉我发生了什么,出了什么问题?

【问题讨论】:

  • 那么gameDuration 是怎么称呼的?如果你在没有先清除间隔的情况下继续调用该函数,它会不断向全局添加一个新间隔,并且旧间隔的处理程序会丢失,并且无法再清除。
  • 您是同时运行多款游戏,还是一次只能运行一款游戏?如果您提供一个可以运行并重现问题的 sn-p,这个问题会更清楚。
  • 将 clearGameInterval1 设置为 0 并检查
  • gameDuration 在你点击开始按钮时被调用,它在点击时附加了这个函数: function startGame(bubbleSpawnInterval) { if (!bubbleSpawnInterval) { alert('请选择一个难度!'); } 其他 { 初始化变量();游戏持续时间();环形(); randomTimers(bubbleSpawnInterval);难度级别(bubbleSpawnInterval); }; }

标签: javascript setinterval clearinterval


【解决方案1】:

在这个问题上花了2天多的时间,我终于找到了错误..都是我的:(。我正在开始游戏,游戏计数器 startGame() 中的 gameDuration();

function startGame(bubbleSpawnInterval) {
if (!bubbleSpawnInterval) {
    alert('Please select a difficulty!');
} else {
    initializingVariavles();
    loop();
    gameDuration();
    randomTimers(bubbleSpawnInterval);
    difficultyLevel(bubbleSpawnInterval);

};

}; 在难度级别(bubbleSpawnInterval)中,我正在清除所有 3 个间隔,但我在同一个函数中设置了另外 2 个(正在工作的),而计数器间隔仍然被清除......我只需将 gameDuration() 函数放在之后使其工作的难度级别(bubbleSpawnInterval)。

function startGame(bubbleSpawnInterval) {
    if (!bubbleSpawnInterval) {
        alert('Please select a difficulty!');
    } else {
        initializingVariavles();
        loop();
        randomTimers(bubbleSpawnInterval);
        difficultyLevel(bubbleSpawnInterval);
        gameDuration();
    };
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-02
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 2015-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多