russell newton
russell newton

Reputation: 109

simple timer- why does a function call inside a function using setTimeout() fail?

I am learning some JavaScript and experimenting with a simple countdown timer. The countdown fails if I insert checkTime() in the timedCount() function. I want the script to display a message in the 'warning' div, when the seconds remaining (var c) is a given integer (in this case 100 sec). When I insert the checkTime() function the script displays 100 and stops. It does the same when I put the function inside timeCount() function. I'm stumped!

var c = 120;
var t;
var timer_is_on = 0;
start.onclick = startCount;
reset.onclick = resetCount;

function timedCount() {
  document.getElementById("clock").innerHTML = c;
  c = c - 1;
  checkTime();
  t = setTimeout(function() {
    timedCount()
  }, 1000);
}

function startCount() {
  if (!timer_is_on) {
    timer_is_on = 1;
    timedCount();
    document.getElementById('start').style.display = 'none';
    document.getElementById('reset').style.display = 'none';
    document.getElementById('stop').style.display = 'block';
  }
}

function stopCount() {
  clearTimeout(t);
  timer_is_on = 0;
  document.getElementById('start').style.display = 'block';
  document.getElementById("start").innerHTML = "Resume";
  document.getElementById('reset').style.display = 'block';
  document.getElementById('stop').style.display = 'none';

}

function resetCount() {
  clearTimeout(t);
  c = 0;
  timer_is_on = 0;
  document.getElementById("txt").value = 0;
  document.getElementById('start').style.display = 'block';
  document.getElementById("start").innerHTML = "Start!";

}

function checkTime() {
  if (c = 100) {
    document.getElementById("warning").innerHTML = "Time nearly up!";
  }
}
<div style="font-size:30px;"><span id="clock">0</span>
  <span>:seconds</span></div>
<div id="warning"></div>
<button id="start">Start count!</button>
<button id="stop" onclick="stopCount()">Pause!</button>
<button id="reset">Reset!</button>

Upvotes: 0

Views: 64

Answers (1)

Adam Diament
Adam Diament

Reputation: 4880

(c = 100) should be (c === 100), you are trying to set when you mean to check for equality.

Upvotes: 0

Related Questions