On/Off一键定时器Javascript

On/Off One Button Timer Javascript

本文关键字:定时器 Javascript 一键 Off On      更新时间:2023-09-26

我正在做一个游戏项目,我正试图为大炮充电做一个计时器。我正试图在同一个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。

谢谢你的帮助!

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

创建interval时,会分配unqiue 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来递增变量,而计时器变量将变量更改为下面的"测试"

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);
    };