javascript countdown timer with start & stop buttons

前端 未结 4 736
孤城傲影
孤城傲影 2021-01-06 02:29

I need to make a simple countdown timer from 5 to zero, with the buttons to START and STOP the counter. The only thing that I don\'t know is that why won\'t my counter stop.

4条回答
  •  渐次进展
    2021-01-06 02:53

    This solution worked for me in react JS

    let Timer =(function(){
        let timerObject;
        let callback=null;
        let seconds=0;
        let counter=()=>{
            seconds++;
            console.log("seconds",seconds);
            if (callback!==undefined) callback(seconds);
        }
        let setCallback=(_callback)=>{callback=_callback }
        let getSeconds=()=>{ return seconds;}
        let reset=()=>{ seconds=0;}
        let start=()=>{timerObject=setInterval(counter,1000);}
        let end=()=>{clearInterval(timerObject);}
        return {"start":start,"end":end, "getSeconds":getSeconds, "reset":reset,"setCallback":setCallback}; })();
    
    export default Timer;
    

提交回复
热议问题