Home > Back-end >  Countdown timer jquery on reset it runs faster then time set
Countdown timer jquery on reset it runs faster then time set

Time:03-18

I am trying to make a countdown timer where I can change the value of the countdown or rest the countdown but I am not able to clear the last timer so the value of the timer is added again to speed if increased please help me I am also sharing the code.

 var sec = $("#timer_this").val();


        $("#start").click(function() {
            var sec = $("#timer_this").val();
            startTimer('start');
        });

        $("#reset").click(function() {
            $("#timer").html(0);
            var timex = 0;
            clearTimeout(timex);
            var timex = 0;
            startTimer('start');

        });


        $("#stop").click(function() {
            $("#timer").html($("#timer_this").val());
            clearTimeout(timex);
        });




        function startTimer() {
            timex = setInterval(function() {
                //document.getElementById('timer').innerHTML = sec   "sec left";
                $("#timer").html(sec);
                sec--;
                if (sec == -1) {
                    clearInterval(timex);
                    time = null;
                    alert("Time out!! :(");
                }

            }, 1000);

        }

        $("#stopbtn").click(function() {
            clearTimeout(timex);
        });
<script src="https://code.jquery.com/jquery-2.0.3.min.js" integrity="sha256-sTy1mJ4I/LAjFCCdEB4RAvPSmRCb3CU7YqodohyeOLo=" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

<input type="text" id="timer_this" value="1000">
    <span id="timer"></span>
    <button id="start">start</button>
    <button id="stop">stop</button>
    <button id="pause">pause</button>
    <button id="reset">reset</button>

CodePudding user response:

several little things to have a working sample :

  • var timex; should be declared globally if you want to set is value in the several callbacks
  • in the reset callback you do var timex = 0; first issue you recreate a local function variable timex but you to do it twice that is not valid
  • for the reset function you can simplyfy it by :
  1. create a stop function

  2. your reset callback became

     $("#reset").click(function() {
        stopTimer();
        startTimer();
     });
    

var sec = $("#timer_this").val();
var timex;

$("#start").click(function() {
  var sec = $("#timer_this").val();
  startTimer('start');
});

$("#reset").click(function() {
  stopTimer();
  startTimer();
});


$("#stop").click(stopTimer);

function stopTimer() {
  $("#timer").html($("#timer_this").val());
  clearTimeout(timex);
  timex = undefined;
}

function startTimer() {
  if (!timex) {
    sec = $("#timer_this").val();
  }
  timex = setInterval(function() {
    $("#timer").html(sec);
    sec--;
    if (sec == -1) {
      clearInterval(timex);
      time = null;
      alert("Time out!! :(");
    }

  }, 1000);

}

$("#pause").click(function() {
  clearTimeout(timex);
});
<script src="https://code.jquery.com/jquery-2.0.3.min.js" integrity="sha256-sTy1mJ4I/LAjFCCdEB4RAvPSmRCb3CU7YqodohyeOLo=" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

<input type="text" id="timer_this" value="1000">
<span id="timer"></span>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="pause">pause</button>
<button id="reset">reset</button>

CodePudding user response:

The timex variable was assigned in the scope of the startTimer function and is lost once that function returns, so it is not available when you later come to call clearTimeout on it.

When building out your logic, its often useful to create functions that describe the actions you want to happen, then call them from your UI components. This helps make the code more readable and reduces repetition.

For example, it's simpler to have clearTimeout in one place, and just call it from whichever methods need to stop the timer. It also helps later when getting the UI to reflect the current state of the application since there's only one way to get to that state.

Here's an example of this sort of approach:

let timerx, sec;

$("#start").click(function() {
  // Toggle between start/stop
  sec ? stopTimer() : startTimer();
});

$("#pause").click(function() {
  // Toggle between pause/resume
  timerx ? pauseTimer() : resumeTimer();
});

function startTimer() {
  // Stop any existing timer
  stopTimer();
  
  // Grab the new count
  sec = parseInt($("#timer_this").val());
  
  // Start the timer
  resumeTimer();
  
  $("#start").text("stop");
  $("#pause").prop("disabled", false);
}

function resumeTimer() {
  // Start timer
  timerx = setInterval(() => {
    // Update time remaining
    $("#timer").text(--sec);
    
    if (sec === 0) {
      // Handle timeout
      stopTimer();
      alert("Time out!! :(");
    }
  }, 1000);
  $("#timer").text(sec);
  $("#pause").text("pause");
}

function stopTimer() {
  // Start timer and clear remainng time
  sec = 0;
  pauseTimer();
  $("#timer").text("");
  $("#start").text("start");
  $("#pause").prop("disabled", true);
}

function pauseTimer() {
  // Just stop the timer
  timerx = clearInterval(timerx);
  $("#pause").text("resume");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input type="number" id="timer_this" value="1000">
<button id="start">start</button>
<button id="pause" disabled>pause</button>
<p id="timer"></p>

  • Related