Search code examples
jquerytimer

Stop timer and reset with simple jQuery


I have a timer counting up. At keypress I want it to stop, and be able to call action that reset it. I have tried but it just wont work obviously because I am missing something in the code, but what? Right now it creates an overlaping counter, so there are two counters adding html to the same div. Here is the code I have tried:

jQuery

 // Variables
    var running = false;

// Timer Function
function timerCount(pad) {
    // Timer
    if (running == true) {
        var pad = function (n) { return ('' + n).length < 4 ? pad('0' + n) : n; };
        jQuery.fn.timer = function () {
            var t = this, i = 0;
            setInterval(function () {
                t.text(pad(i++));
            }, 1000);
        };
        $("#timer").timer();
    } else {
        pad = 0;
        window.clearInterval(timer);
    }
}

// Start Timer
$(document).ready(function () {
     running = true;
     timerCount();
});

// Stop Function
function stoptimer() {
    running = false;
    pad = 0;
    window.clearInterval(timer);
}

// Reset Function
function reset() {
    pad = 0;
    window.clearInterval(timer);
    running = true;
    timerCount();
}

$("body").keydown(function (e) {

     // X
    if (e.keyCode == 88) {   
       reset();
    }

     // H
if (e.keyCode == 72) {   
   stoptimer();
    }
});

html

<div id="timer"></div>

I tried several solutions that was found here on stackoverflow but none that helped me do it in this super jQuery simple way as I wanted it to work. There are super advanced timers and clocks but I just don't know how to convert them to this more simple version.

You can see I have tried some of this solution: start-stop-reset simple timer using jQuery


Solution

  • Comments in code:

    // Variables
    let running = false;
    let timer; // make timer global
    
    // Helper functions
    const pad = n => String(n).padStart(4, "0");
    
    // jQuery plugins
    jQuery.fn.timer = function() {
      let i = 0;
      timer = setInterval(() => { // you need to store setTimeout into timer
        this.text(pad(i++));
      }, 1000); // This is not accurate, but that's for another question
    };
    
    // Timer Function
    // function timerCount() { // not needed
    
    
    // Stop Function
    const stoptimer = () => {
      clearInterval(timer);
      $("#timer").text(pad(0))
    };
    
    // Reset Function
    const reset = () => {
      stoptimer();  // Reuse your functions!
      $("#timer").timer();
    };
    
    $("body").on("keydown", (evt) => {
    
      if (evt.key === "x") reset();  // use .key instead of .keyCode
      if (evt.key === "h") stoptimer();
      
    });
    
    // Init
    reset();
    Use keys <kbd>x</kbd> to reset and <kbd>h</kbd> to stop the timer. 
    <div id="timer"></div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>