0
votes

I'm trying to get a jquery function to approach different numbers in the same timeframe in a list by incrementing/decrementing where required. That is I have a list:

// (initialised outside the function scope)
var numbers = [10, 5, 13, 1, 1000];
var curNumber = 0;
var i = 0;

The function should take the same amount of time (e.g. 1 second) to reach from curNumber = 0 to number[0] = 10 as it would from curNumber = 0 to number[4] = 1000. In the list above, the code would finish each loop in 1 second, from 0 to 10 to 5 to 13 to 1 to 1000 (total 5 seconds if curNumber = 0 initially).

What I'm aiming for is a simple function to run continuously such as:

while(true) {
    if (curNumber < numbers[i])
      curNumber++;
    else if (curNumber > numbers[i])
      curNumber--;

    if (curNumber == numbers[i]) {
      alert(numbers[i] + " number reached!");
      i > numbers.length ? i = 0 : i ++;
    }
}

A timer button looks like so:

$("#start").click(function() {
   myTimerFunction();
});

Should I make use of the var refreshId = setInterval(function() {}, 1000); function? - or is it something that would just run the function each 1000 milliseconds irrelevant of how fast the numbers are approached?

2

2 Answers

1
votes

I'm not completely sure what do you mean by "change the rate", but if the delay between calls is going to change during execution (i.e., the process should speed up or slow down) then I would use setTimeout() to let the function queue up the next invocation of itself, with a variable to specify the delay:

var delay = 1000;
function myTimerFunction() {
    // do something
    // ...
    if (someCondition) {
       // change delay somehow
    }
    setTimeout(myTimerFunction, delay);
}

If the interval is to stay the same then setInterval() is OK, though I personally prefer to use setTimeout() either way because I usually find it simpler to have code like:

    if (someCondition)
       setTimeout(myTimerFunction, delay);

...to decide whether to keep "looping" rather than saving an interval id and then calling clearInterval() before later calling setInterval() again.

0
votes

Using a holder variable refreshId like that should be fine. To change the timer, you'd just have something like this:

var numberStep = function () {
  if (curNumber < number[i])
    curNumber++;
  else if (curNumber > number[i])
    curNumber--;

  if (curNumber == number[i]){
    alert(number[i] + " number reached!");
    i++; //(or if i > numbers.length change to 0)
  }
};

var myTimerFunction ( interval, currentTimer ) {
  if ( currentTimer ) clearInterval(currentTimer);
  return setInterval( numberStep, interval );
};

var refreshId = myTimerFunction( startingInterval );

Then whenever you wanted to change the interval, you could just use refreshId = myTimerFunction( newInterval, refreshId );. In the example you gave in the comment there, you'd set startingInterval to 1000 and newInterval to 500.