0

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?

4

2 回答 2

1

我不完全确定“更改速率”是什么意思,但如果调用之间的延迟在执行期间会发生变化(即进程应该加快或减慢),那么我会使用setTimeout()让函数排队自己的下一次调用,用一个变量来指定延迟:

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

如果间隔保持不变,那么setInterval()就可以了,尽管我个人更喜欢使用setTimeout()任何一种方式,因为我通常发现使用如下代码更简单:

    if (someCondition)
       setTimeout(myTimerFunction, delay);

...决定是否继续“循环”而不是保存间隔 id,然后clearInterval()在稍后再次调用之前调用setInterval()

于 2013-10-27T04:16:03.133 回答
0

使用这样的持有者变量 refreshId 应该没问题。要更改计时器,您只需要以下内容:

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 );

然后,每当您想更改间隔时,只需使用refreshId = myTimerFunction( newInterval, refreshId );. 在您在评论中给出的示例中,您设置startingInterval为 1000 和newInterval500。

于 2013-10-27T04:17:53.823 回答