On/Off 一键定时器 Javascript

On/Off One Button Timer Javascript

我正在做一个游戏项目,我正在尝试为加农炮充电做一个计时器。我正在尝试在同一个 onClick 按钮上使用 setInverval 和 clearInterval 来控制此类计时器。

这是我的代码:

function playerOneCharge(){
    if(pOnePower==0){
    pOnePower = setInterval(function(){ myTimer()}, 100);
    }else{
        clearInterval(pOnePower);
    }
}

function myTimer(){
    ++pOnePower;
    console.log(pOnePower);
};

按下按钮时触发playerOneCharge,pOnePower设置为0。

感谢您的帮助!

它没有停止,因为您使用相同的变量来计算和创建间隔。

创建间隔时,未分配 id,clearInterval 需要清除该 id。

但是你增加了那个 id 值 ++pOnePower 所以当涉及到 clearInterval 时他需要间隔 id 而不是他得到另一个间隔

中不存在的信息

将两个变量分开

像这样

var pOnePower=0;
var intVal=null;
function playerOneCharge(){
    console.log(pOnePower);
    if(!intVal){
    intVal = setInterval(function(){ myTimer()}, 100);
    }else{
        clearInterval(intVal);
        intVal=null;
    }
}

function myTimer(){
    ++pOnePower;
   console.log(pOnePower);
};

JSFIDDLE

好的,这里的问题是您正在使用相同的变量 pOnePower 来递增变量和计时器变量,将变量更改为如下所示的其他内容,如 'Test'

var Test;
    function playerOneCharge(){
        if(pOnePower==0){
        Test= setInterval(function(){ myTimer()}, 100);
        }else{
            clearInterval(Test);
        }
    }

    function myTimer(){
        ++pOnePower;
        console.log(pOnePower);
    };

您的问题是您正在使用 setInterval。正确的方法是setTimeout和对应的clearTimeout。

var pOnePower;

function playerOneCharge(){
    if(pOnePower==0){
    pOnePower = setTimeout(function(){ myTimer()}, 100);
    }else{
        clearTimeout(pOnePower);
    }
}

function myTimer(){
    ++pOnePower;
    console.log(pOnePower);
};
    function myTimer(){
        ++pOnePower;
        console.log(pOnePower);
    };