1

Im using a function to start a count up timer using moment.js library , how could I make a stop timer function?

function startTimer()
{
var startTimestamp = moment().startOf("day");
setInterval(function() {
    startTimestamp.add(1, 'second');
    document.getElementById('timer').innerHTML =  
    startTimestamp.format('HH:mm:ss'); }, 1000);
  }
  startTimer();

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

Thanks in advance

Claudio Martinez
  • 297
  • 1
  • 4
  • 17
  • Possible duplicate of [setTimeout / clearTimeout problems](https://stackoverflow.com/questions/3015319/settimeout-cleartimeout-problems) – VincenzoC Jun 04 '18 at 08:09

1 Answers1

0
    function startTimer() {
        var startTimestamp = moment().startOf("day");
        var myInterval = setInterval(function () {
            startTimestamp.add(1, 'second');
            document.getElementById('timer').innerHTML =
                startTimestamp.format('HH:mm:ss');
        }, 1000);
    }
    startTimer();

    function stopTimer() {
        clearInterval(myInterval);
    }
  1. Store your interval in a variable. I called it myInterval.
  2. Create a new function called stopTimer(); that uses the clearInterval() method to clear your interval.
  3. Create your button or whatever DOM element to trigger this, and set the onClick to stopTimer();
CodeSpent
  • 1,684
  • 4
  • 23
  • 46