Countdown Timer not Stopping with clearInterval()











up vote
0
down vote

favorite












I'm having a problem get this countdown timer to stop at zero so the time won't show as a negative value. The console.log is getting called and works fine but for some reason the clearInterval() is not. This is driving me crazy and I'm close to quitting.






const timerContainer = document.getElementById('timerContainer');   

const THREEMINUTES = 60 * 0.1;//5 seconds for testing

startTimer(THREEMINUTES, timerContainer);

function startTimer(duration, display) {

let start = Date.now();
let diff, min, sec;

let timer = () => {
diff = duration - (((Date.now() - start) / 1000) | 0);
//use bitwise to truncate the float
min = (diff / 60) | 0;
sec = (diff % 60) | 0;

min = min < 10 ? '0' + min : min;
sec = sec < 10 ? '0' + sec : sec;

display.textContent = min + ':' + sec;

if (diff <= 0) {
stopTimer();
submit.disabled = 'true';
};

};

//call timer immediately otherwise we wait a full second
timer();
setInterval(timer, 1000);

function stopTimer() {
clearInterval(timer);
console.log("time's up", diff);
};
}

<div id="timerContainer"></div>












share|improve this question




























    up vote
    0
    down vote

    favorite












    I'm having a problem get this countdown timer to stop at zero so the time won't show as a negative value. The console.log is getting called and works fine but for some reason the clearInterval() is not. This is driving me crazy and I'm close to quitting.






    const timerContainer = document.getElementById('timerContainer');   

    const THREEMINUTES = 60 * 0.1;//5 seconds for testing

    startTimer(THREEMINUTES, timerContainer);

    function startTimer(duration, display) {

    let start = Date.now();
    let diff, min, sec;

    let timer = () => {
    diff = duration - (((Date.now() - start) / 1000) | 0);
    //use bitwise to truncate the float
    min = (diff / 60) | 0;
    sec = (diff % 60) | 0;

    min = min < 10 ? '0' + min : min;
    sec = sec < 10 ? '0' + sec : sec;

    display.textContent = min + ':' + sec;

    if (diff <= 0) {
    stopTimer();
    submit.disabled = 'true';
    };

    };

    //call timer immediately otherwise we wait a full second
    timer();
    setInterval(timer, 1000);

    function stopTimer() {
    clearInterval(timer);
    console.log("time's up", diff);
    };
    }

    <div id="timerContainer"></div>












    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I'm having a problem get this countdown timer to stop at zero so the time won't show as a negative value. The console.log is getting called and works fine but for some reason the clearInterval() is not. This is driving me crazy and I'm close to quitting.






      const timerContainer = document.getElementById('timerContainer');   

      const THREEMINUTES = 60 * 0.1;//5 seconds for testing

      startTimer(THREEMINUTES, timerContainer);

      function startTimer(duration, display) {

      let start = Date.now();
      let diff, min, sec;

      let timer = () => {
      diff = duration - (((Date.now() - start) / 1000) | 0);
      //use bitwise to truncate the float
      min = (diff / 60) | 0;
      sec = (diff % 60) | 0;

      min = min < 10 ? '0' + min : min;
      sec = sec < 10 ? '0' + sec : sec;

      display.textContent = min + ':' + sec;

      if (diff <= 0) {
      stopTimer();
      submit.disabled = 'true';
      };

      };

      //call timer immediately otherwise we wait a full second
      timer();
      setInterval(timer, 1000);

      function stopTimer() {
      clearInterval(timer);
      console.log("time's up", diff);
      };
      }

      <div id="timerContainer"></div>












      share|improve this question















      I'm having a problem get this countdown timer to stop at zero so the time won't show as a negative value. The console.log is getting called and works fine but for some reason the clearInterval() is not. This is driving me crazy and I'm close to quitting.






      const timerContainer = document.getElementById('timerContainer');   

      const THREEMINUTES = 60 * 0.1;//5 seconds for testing

      startTimer(THREEMINUTES, timerContainer);

      function startTimer(duration, display) {

      let start = Date.now();
      let diff, min, sec;

      let timer = () => {
      diff = duration - (((Date.now() - start) / 1000) | 0);
      //use bitwise to truncate the float
      min = (diff / 60) | 0;
      sec = (diff % 60) | 0;

      min = min < 10 ? '0' + min : min;
      sec = sec < 10 ? '0' + sec : sec;

      display.textContent = min + ':' + sec;

      if (diff <= 0) {
      stopTimer();
      submit.disabled = 'true';
      };

      };

      //call timer immediately otherwise we wait a full second
      timer();
      setInterval(timer, 1000);

      function stopTimer() {
      clearInterval(timer);
      console.log("time's up", diff);
      };
      }

      <div id="timerContainer"></div>








      const timerContainer = document.getElementById('timerContainer');   

      const THREEMINUTES = 60 * 0.1;//5 seconds for testing

      startTimer(THREEMINUTES, timerContainer);

      function startTimer(duration, display) {

      let start = Date.now();
      let diff, min, sec;

      let timer = () => {
      diff = duration - (((Date.now() - start) / 1000) | 0);
      //use bitwise to truncate the float
      min = (diff / 60) | 0;
      sec = (diff % 60) | 0;

      min = min < 10 ? '0' + min : min;
      sec = sec < 10 ? '0' + sec : sec;

      display.textContent = min + ':' + sec;

      if (diff <= 0) {
      stopTimer();
      submit.disabled = 'true';
      };

      };

      //call timer immediately otherwise we wait a full second
      timer();
      setInterval(timer, 1000);

      function stopTimer() {
      clearInterval(timer);
      console.log("time's up", diff);
      };
      }

      <div id="timerContainer"></div>





      const timerContainer = document.getElementById('timerContainer');   

      const THREEMINUTES = 60 * 0.1;//5 seconds for testing

      startTimer(THREEMINUTES, timerContainer);

      function startTimer(duration, display) {

      let start = Date.now();
      let diff, min, sec;

      let timer = () => {
      diff = duration - (((Date.now() - start) / 1000) | 0);
      //use bitwise to truncate the float
      min = (diff / 60) | 0;
      sec = (diff % 60) | 0;

      min = min < 10 ? '0' + min : min;
      sec = sec < 10 ? '0' + sec : sec;

      display.textContent = min + ':' + sec;

      if (diff <= 0) {
      stopTimer();
      submit.disabled = 'true';
      };

      };

      //call timer immediately otherwise we wait a full second
      timer();
      setInterval(timer, 1000);

      function stopTimer() {
      clearInterval(timer);
      console.log("time's up", diff);
      };
      }

      <div id="timerContainer"></div>






      javascript clearinterval






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 7 at 15:54









      Scott Marcus

      37.9k51936




      37.9k51936










      asked Nov 7 at 15:11









      Chris Carr

      105




      105
























          3 Answers
          3






          active

          oldest

          votes

















          up vote
          3
          down vote



          accepted










          You are not saving the result of setInterval(timer, 1000);



          you should use this:



          let timerId;
          timer();
          timerId = setInterval(timer, 1000);

          function stopTimer() {
          clearInterval(timerId);
          console.log("time's up", diff)
          };


          As you might see, the result of setInterval is a number (object in node), and all you then need to do is pass that value to clearInterval thus we save the value in the variable timerId for reference.






          share|improve this answer




























            up vote
            2
            down vote













            Don't pass the function that you want stopped to clearInterval().



            Pass a reference to the timer that you started, so you need to make sure that when you start a timer, you capture a reference to the ID that will be returned from it.



            // Function that the timer will invoke
            function callback(){
            . . .
            }

            // Set up and initiate a timer and capture a reference to its unique ID
            var timerID = setInterval(callback, 1000);

            // When needed, cancel the timer by passing the reference to it
            clearInterval(timerID);





            share|improve this answer






























              up vote
              0
              down vote













              The code is fixed make sure you fix your submit button code.
              You should first assign the value of setInterval to a variable. That variable is used while calling clearInterval which infact clears the interval.



              const timerContainer = document.getElementById('timerContainer');   

              const THREEMINUTES = 60 * 0.1;//5 seconds for testing

              startTimer(THREEMINUTES, timerContainer);
              var timer = null;
              function startTimer(duration, display) {

              let start = Date.now();
              let diff, min, sec;

              let timer = () => {
              diff = duration - (((Date.now() - start) / 1000) | 0);
              //use bitwise to truncate the float
              min = (diff / 60) | 0;
              sec = (diff % 60) | 0;

              min = min < 10 ? '0' + min : min;
              sec = sec < 10 ? '0' + sec : sec;

              display.textContent = min + ':' + sec;

              if (diff <= 0) {
              stopTimer();
              submit.disabled = 'true';
              };

              };

              //call timer immediately otherwise we wait a full second
              timer();
              timer = setInterval(timer, 1000);

              function stopTimer() {
              clearInterval(timer);
              console.log("time's up", diff);
              };
              }





              share|improve this answer



















              • 2




                Answers shouldn't just be working code. They should explain what the problem was and how you solved it.
                – Scott Marcus
                Nov 7 at 15:22










              • You are resetting the value of timer
                – Get Off My Lawn
                Nov 7 at 15:25













              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














               

              draft saved


              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53192266%2fcountdown-timer-not-stopping-with-clearinterval%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              3
              down vote



              accepted










              You are not saving the result of setInterval(timer, 1000);



              you should use this:



              let timerId;
              timer();
              timerId = setInterval(timer, 1000);

              function stopTimer() {
              clearInterval(timerId);
              console.log("time's up", diff)
              };


              As you might see, the result of setInterval is a number (object in node), and all you then need to do is pass that value to clearInterval thus we save the value in the variable timerId for reference.






              share|improve this answer

























                up vote
                3
                down vote



                accepted










                You are not saving the result of setInterval(timer, 1000);



                you should use this:



                let timerId;
                timer();
                timerId = setInterval(timer, 1000);

                function stopTimer() {
                clearInterval(timerId);
                console.log("time's up", diff)
                };


                As you might see, the result of setInterval is a number (object in node), and all you then need to do is pass that value to clearInterval thus we save the value in the variable timerId for reference.






                share|improve this answer























                  up vote
                  3
                  down vote



                  accepted







                  up vote
                  3
                  down vote



                  accepted






                  You are not saving the result of setInterval(timer, 1000);



                  you should use this:



                  let timerId;
                  timer();
                  timerId = setInterval(timer, 1000);

                  function stopTimer() {
                  clearInterval(timerId);
                  console.log("time's up", diff)
                  };


                  As you might see, the result of setInterval is a number (object in node), and all you then need to do is pass that value to clearInterval thus we save the value in the variable timerId for reference.






                  share|improve this answer












                  You are not saving the result of setInterval(timer, 1000);



                  you should use this:



                  let timerId;
                  timer();
                  timerId = setInterval(timer, 1000);

                  function stopTimer() {
                  clearInterval(timerId);
                  console.log("time's up", diff)
                  };


                  As you might see, the result of setInterval is a number (object in node), and all you then need to do is pass that value to clearInterval thus we save the value in the variable timerId for reference.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 7 at 15:14









                  Get Off My Lawn

                  12.9k1678162




                  12.9k1678162
























                      up vote
                      2
                      down vote













                      Don't pass the function that you want stopped to clearInterval().



                      Pass a reference to the timer that you started, so you need to make sure that when you start a timer, you capture a reference to the ID that will be returned from it.



                      // Function that the timer will invoke
                      function callback(){
                      . . .
                      }

                      // Set up and initiate a timer and capture a reference to its unique ID
                      var timerID = setInterval(callback, 1000);

                      // When needed, cancel the timer by passing the reference to it
                      clearInterval(timerID);





                      share|improve this answer



























                        up vote
                        2
                        down vote













                        Don't pass the function that you want stopped to clearInterval().



                        Pass a reference to the timer that you started, so you need to make sure that when you start a timer, you capture a reference to the ID that will be returned from it.



                        // Function that the timer will invoke
                        function callback(){
                        . . .
                        }

                        // Set up and initiate a timer and capture a reference to its unique ID
                        var timerID = setInterval(callback, 1000);

                        // When needed, cancel the timer by passing the reference to it
                        clearInterval(timerID);





                        share|improve this answer

























                          up vote
                          2
                          down vote










                          up vote
                          2
                          down vote









                          Don't pass the function that you want stopped to clearInterval().



                          Pass a reference to the timer that you started, so you need to make sure that when you start a timer, you capture a reference to the ID that will be returned from it.



                          // Function that the timer will invoke
                          function callback(){
                          . . .
                          }

                          // Set up and initiate a timer and capture a reference to its unique ID
                          var timerID = setInterval(callback, 1000);

                          // When needed, cancel the timer by passing the reference to it
                          clearInterval(timerID);





                          share|improve this answer














                          Don't pass the function that you want stopped to clearInterval().



                          Pass a reference to the timer that you started, so you need to make sure that when you start a timer, you capture a reference to the ID that will be returned from it.



                          // Function that the timer will invoke
                          function callback(){
                          . . .
                          }

                          // Set up and initiate a timer and capture a reference to its unique ID
                          var timerID = setInterval(callback, 1000);

                          // When needed, cancel the timer by passing the reference to it
                          clearInterval(timerID);






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Nov 7 at 15:30

























                          answered Nov 7 at 15:14









                          Scott Marcus

                          37.9k51936




                          37.9k51936






















                              up vote
                              0
                              down vote













                              The code is fixed make sure you fix your submit button code.
                              You should first assign the value of setInterval to a variable. That variable is used while calling clearInterval which infact clears the interval.



                              const timerContainer = document.getElementById('timerContainer');   

                              const THREEMINUTES = 60 * 0.1;//5 seconds for testing

                              startTimer(THREEMINUTES, timerContainer);
                              var timer = null;
                              function startTimer(duration, display) {

                              let start = Date.now();
                              let diff, min, sec;

                              let timer = () => {
                              diff = duration - (((Date.now() - start) / 1000) | 0);
                              //use bitwise to truncate the float
                              min = (diff / 60) | 0;
                              sec = (diff % 60) | 0;

                              min = min < 10 ? '0' + min : min;
                              sec = sec < 10 ? '0' + sec : sec;

                              display.textContent = min + ':' + sec;

                              if (diff <= 0) {
                              stopTimer();
                              submit.disabled = 'true';
                              };

                              };

                              //call timer immediately otherwise we wait a full second
                              timer();
                              timer = setInterval(timer, 1000);

                              function stopTimer() {
                              clearInterval(timer);
                              console.log("time's up", diff);
                              };
                              }





                              share|improve this answer



















                              • 2




                                Answers shouldn't just be working code. They should explain what the problem was and how you solved it.
                                – Scott Marcus
                                Nov 7 at 15:22










                              • You are resetting the value of timer
                                – Get Off My Lawn
                                Nov 7 at 15:25

















                              up vote
                              0
                              down vote













                              The code is fixed make sure you fix your submit button code.
                              You should first assign the value of setInterval to a variable. That variable is used while calling clearInterval which infact clears the interval.



                              const timerContainer = document.getElementById('timerContainer');   

                              const THREEMINUTES = 60 * 0.1;//5 seconds for testing

                              startTimer(THREEMINUTES, timerContainer);
                              var timer = null;
                              function startTimer(duration, display) {

                              let start = Date.now();
                              let diff, min, sec;

                              let timer = () => {
                              diff = duration - (((Date.now() - start) / 1000) | 0);
                              //use bitwise to truncate the float
                              min = (diff / 60) | 0;
                              sec = (diff % 60) | 0;

                              min = min < 10 ? '0' + min : min;
                              sec = sec < 10 ? '0' + sec : sec;

                              display.textContent = min + ':' + sec;

                              if (diff <= 0) {
                              stopTimer();
                              submit.disabled = 'true';
                              };

                              };

                              //call timer immediately otherwise we wait a full second
                              timer();
                              timer = setInterval(timer, 1000);

                              function stopTimer() {
                              clearInterval(timer);
                              console.log("time's up", diff);
                              };
                              }





                              share|improve this answer



















                              • 2




                                Answers shouldn't just be working code. They should explain what the problem was and how you solved it.
                                – Scott Marcus
                                Nov 7 at 15:22










                              • You are resetting the value of timer
                                – Get Off My Lawn
                                Nov 7 at 15:25















                              up vote
                              0
                              down vote










                              up vote
                              0
                              down vote









                              The code is fixed make sure you fix your submit button code.
                              You should first assign the value of setInterval to a variable. That variable is used while calling clearInterval which infact clears the interval.



                              const timerContainer = document.getElementById('timerContainer');   

                              const THREEMINUTES = 60 * 0.1;//5 seconds for testing

                              startTimer(THREEMINUTES, timerContainer);
                              var timer = null;
                              function startTimer(duration, display) {

                              let start = Date.now();
                              let diff, min, sec;

                              let timer = () => {
                              diff = duration - (((Date.now() - start) / 1000) | 0);
                              //use bitwise to truncate the float
                              min = (diff / 60) | 0;
                              sec = (diff % 60) | 0;

                              min = min < 10 ? '0' + min : min;
                              sec = sec < 10 ? '0' + sec : sec;

                              display.textContent = min + ':' + sec;

                              if (diff <= 0) {
                              stopTimer();
                              submit.disabled = 'true';
                              };

                              };

                              //call timer immediately otherwise we wait a full second
                              timer();
                              timer = setInterval(timer, 1000);

                              function stopTimer() {
                              clearInterval(timer);
                              console.log("time's up", diff);
                              };
                              }





                              share|improve this answer














                              The code is fixed make sure you fix your submit button code.
                              You should first assign the value of setInterval to a variable. That variable is used while calling clearInterval which infact clears the interval.



                              const timerContainer = document.getElementById('timerContainer');   

                              const THREEMINUTES = 60 * 0.1;//5 seconds for testing

                              startTimer(THREEMINUTES, timerContainer);
                              var timer = null;
                              function startTimer(duration, display) {

                              let start = Date.now();
                              let diff, min, sec;

                              let timer = () => {
                              diff = duration - (((Date.now() - start) / 1000) | 0);
                              //use bitwise to truncate the float
                              min = (diff / 60) | 0;
                              sec = (diff % 60) | 0;

                              min = min < 10 ? '0' + min : min;
                              sec = sec < 10 ? '0' + sec : sec;

                              display.textContent = min + ':' + sec;

                              if (diff <= 0) {
                              stopTimer();
                              submit.disabled = 'true';
                              };

                              };

                              //call timer immediately otherwise we wait a full second
                              timer();
                              timer = setInterval(timer, 1000);

                              function stopTimer() {
                              clearInterval(timer);
                              console.log("time's up", diff);
                              };
                              }






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Nov 7 at 15:42

























                              answered Nov 7 at 15:18









                              Shahabaz

                              57110




                              57110








                              • 2




                                Answers shouldn't just be working code. They should explain what the problem was and how you solved it.
                                – Scott Marcus
                                Nov 7 at 15:22










                              • You are resetting the value of timer
                                – Get Off My Lawn
                                Nov 7 at 15:25
















                              • 2




                                Answers shouldn't just be working code. They should explain what the problem was and how you solved it.
                                – Scott Marcus
                                Nov 7 at 15:22










                              • You are resetting the value of timer
                                – Get Off My Lawn
                                Nov 7 at 15:25










                              2




                              2




                              Answers shouldn't just be working code. They should explain what the problem was and how you solved it.
                              – Scott Marcus
                              Nov 7 at 15:22




                              Answers shouldn't just be working code. They should explain what the problem was and how you solved it.
                              – Scott Marcus
                              Nov 7 at 15:22












                              You are resetting the value of timer
                              – Get Off My Lawn
                              Nov 7 at 15:25






                              You are resetting the value of timer
                              – Get Off My Lawn
                              Nov 7 at 15:25




















                               

                              draft saved


                              draft discarded



















































                               


                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53192266%2fcountdown-timer-not-stopping-with-clearinterval%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              這個網誌中的熱門文章

                              Xamarin.form Move up view when keyboard appear

                              Post-Redirect-Get with Spring WebFlux and Thymeleaf

                              Anylogic : not able to use stopDelay()