Joel
Joel

Reputation: 6173

timer with delay, reset and restart? jQuery

So I basically have a timer which counts 1 number every 4 seconds. It stops when it hits 10.

Q: How do i make it so that the timer stops at 10 for a couple of seconds, then starts counting again at 1?

    var i = 8;
setInterval( increment, 4000);
function increment(){
if(i<=10)
{
console.log(i);
 $('.increase').html('').append(i);
i++;
}

}

JSfiddle: http://jsfiddle.net/0t3s8erj/

Upvotes: 0

Views: 748

Answers (2)

jfriend00
jfriend00

Reputation: 707228

You can do it like this where you run an interval timer until you get to the max count, then you clear that timer and start a new timer for the amount of time you want to pause and then when that delay timer fires, you call your function again to start it all over.

Here's a working code snippet (I set the times short here for demo purposes, but you can set them to whatever you want):

function runTimer(selector, start, end, interval, delay) {
    var cntr = start;
    $(selector).html(cntr);
    var timer = setInterval(function() {
        ++cntr;
        $(selector).html(cntr);
        if (cntr >= end) {
            clearInterval(timer);
            setTimeout(function() {
                runTimer(selector, 1, end, interval, delay);
            }, delay);
        }
    }, interval);
}

runTimer('.increase', 8, 10, 300, 2000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="increase">8</span>/10

Upvotes: 1

reg4in
reg4in

Reputation: 574

Use the else!

var counter = 0

function increment () {
  counter++

  if (counter <= 10) {
    console.log(counter)
  } else {
    clearInterval(incrementInterval)

    setTimeout(function () {
      incrementInterval = setInterval(increment, 4000)
    }, 10000)
  }
}

incrementInterval = setInterval(increment, 4000)

Upvotes: 1

Related Questions