Yusaf Khaliq
Yusaf Khaliq

Reputation: 3393

jQuery counter from specified variables

If I have the variables below

$(document).ready(function() {
    var minsecond = 1;
    var maxseconds = 4;
    var updateinterval = 1;
    var interval = updateinterval*1000;
    window.setInterval(function(){
    var currentseconds = ; //value increasing by 1 every var updateinterval (value) in seconds  from var minsecond value until it reaches var maxseconds and resetting to var minsecond value and cycling again
    $("span").html(currentseconds);
    }, interval);
});
​

How do I create a counter which starts at value of var minsecond and goes up by 1 every var updateinterval in seconds to the value var maxsecond and then restarting at var minsecond http://jsfiddle.net/TnNhA/

Upvotes: 1

Views: 137

Answers (4)

mrtsherman
mrtsherman

Reputation: 39872

This should do it. The tricky part is the interval, as it is variable. In my answer I assume you aren't incrementing by whole numbers, but by your interval amount. Hopefully this is how you thought of it too.

http://jsfiddle.net/Vfnjh/1

$(document).ready(function() {
    var minsecond = 1;
    var maxseconds = 4;
    var updateinterval = 1;
    var interval = updateinterval * 1000;
    var currentseconds = minsecond;

    window.setInterval(function() {
        currentseconds += updateinterval;
        if (currentseconds > maxseconds) {
            currentseconds = minsecond;
        }
        $("span").html(currentseconds);
    }, interval);
});​

Upvotes: 0

j08691
j08691

Reputation: 207861

How about this:

var maxseconds = 4;
var updateinterval = 1;
var interval = updateinterval * 1000;

var counter = 1;

window.setInterval(function() {
    $("span").html(counter);
    counter = (counter % maxseconds == 0) ? 1 : counter + 1;
}, interval);​

jsFiddle Example

Upvotes: 0

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

I think something like below is what you want,

DEMO

$(document).ready(function() {
    var minsecond = 1;
    var maxseconds = 4;
    var updateinterval = 1;
    var interval = updateinterval*1000;

    var currentseconds = minsecond;

    window.setInterval(function(){
        if (currentseconds > maxseconds ) {
             currentseconds = minsecond;
        }

        $("span").html(currentseconds++);
    }, interval);
});

Upvotes: 2

shanabus
shanabus

Reputation: 13115

Would something like this work for you?

var currentseconds = 0;
setInterval(yourFunction(), interval);

function yourFunction() {
  if (minsecond >= maxsecond) {
    currentseconds = minsecond;
  }
  else {
    currentseconds++;
  }
  $("span").html(currentseconds);
}

Set up a test to check if currentseconds it reaches your maxsecond var, reset it.

Upvotes: 0

Related Questions