Amauri
Amauri

Reputation: 550

setInterval does not keeep going

When ctdwnDecCall() is called, it displays 8 but only once and it should every second, this script is at the head of the page

    var ctdwnDecInt;
    function ctdwnDecCall()
        {
            ctdwnDecInt=setInterval(ctdwnDec(),1000);
        }
        function ctdwnDec()
        {
            document.write("8");
            
        }

Upvotes: 0

Views: 46

Answers (2)

Mulan
Mulan

Reputation: 135217

I would probably write something like this (JSBIN DEMO)

var Timer = function Timer(elem, seconds) {
  elem = elem;
  seconds = seconds || 10;

  var interval = null;

  function render() {
    elem.innerHTML = seconds;
  }

  function start() {
    if (!interval) {
      interval = setInterval(update, 1000);
    }
  }

  function update() {
    seconds = seconds - 1;
    render();

    if (seconds === 0) {
      stop();
    }
  }

  function stop() {
    clearInterval(interval);
  }

  this.start = start;
  this.stop = stop;
}

Usage becomes easy mode now

HTML

Here we setup a couple timers and use the class timer (you can pick whatever you want)

<span class="timer"></span>
<span class="timer"></span>
<span class="timer"></span>

JavaScript

Find all timers by class timer (or whatever you pick) and initialize a new Timer object for each of them. In this example, we set each timer to have an 8-second countdown.

var timers = document.getElementsByClassName("timer");

for (var i=0, len=timers.length; i<len; i++) {
  var t = new Timer(timers[i], 8);
  t.start();
}

Upvotes: 0

squid314
squid314

Reputation: 1395

You are calling the ctdwnDec function, not setting in up on an interval. You need to remove the ():

var ctdwnDecInt;
function ctdwnDecCall() {
    ctdwnDecInt=setInterval(ctdwnDec ,1000);
              // no parens in there ^
}
function ctdwnDec() {
    document.write("8");
}

Upvotes: 1

Related Questions