segmentationfaulter
segmentationfaulter

Reputation: 1045

How to make window.clearInterval() work with this javascript code?

I was trying to implement a pomodoro clock, before diving into real code, I was playing with window.setInterval() and its counterpart window.clearInterval. The problem I am faced with is that I am unable to make window.clearInterval() work for me. Have a look at my code please and guide me how to make it work. Thank you

var startTime = 11;
var intervalID;

function downCounter() {
  startTime--;
  $('h2').text(startTime);
}

if (startTime > 0)
  intervalID = setInterval(downCounter, 1000);
else
  clearInterval(intervalID);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2></h2>

Upvotes: 0

Views: 134

Answers (3)

Alan
Alan

Reputation: 634

The clearInterval should be called in downCounter function:

    function downCounter() {
      startTime--;
      $('h2').text(startTime);
      if (startTime <= 0 ) {
        clearInterval(intervalID);
      }    
    }

Upvotes: 1

Paul Roub
Paul Roub

Reputation: 36438

The else here:

if (startTime > 0)
  intervalID = setInterval(downCounter, 1000);
else
  clearInterval(intervalID);

will never run.

This block only runs once, before the timer is started, when you know that startTime is > 0.

Check startTime in the handler, and clear the interval there when it's gone too far:

var startTime = 11;
var intervalID;

function downCounter() {
  startTime--;
  $('h2').text(startTime);
  
  if (startTime <= 0)
    clearInterval(intervalID);
}

intervalID = setInterval(downCounter, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2></h2>

Upvotes: 1

MazzCris
MazzCris

Reputation: 1840

In your code, if (startTime > 0) is checked only the first time. Try this way:

$(document).ready(function() {
    var startTime = 11;
    var intervalID;
    function downCounter() {
        startTime--;
        $('h2').text(startTime);
        if (startTime <= 0){
            clearInterval(intervalID);
        }
    }
    intervalID = setInterval(downCounter, 1000);    
});

Upvotes: 2

Related Questions