运行 期间的 setTimeout 更改速度

setTimeout change speed during run

我想在 运行 函数的同时更改 setTimeout 速度。

我想我快到了,但我的脚本仍然有一些问题。但我不知道是什么。

有人可以帮助我吗?

$('input[type="range"]').rangeslider({
        polyfill: false,
        onInit: function() {
        this.update();
    },
        onSlide: function(pos, value) {
        tempPosition = pos + this.grabX;
        position = (tempPosition <= this.handleWidth) ? this.handleWidth : (tempPosition >= this.maxHandleX) ? this.maxHandleX : tempPosition;
        //timer = setTimeout(counter, value);
        //clearTimeout(timer);
        //var speed = value;
        //clearTimeout(timer);
        var timer = 0;
        timer.length = 0;
        timer = setTimeout(counter, value);
        clearTimeout(timer);
        document.getElementById("demo").innerHTML = timer;


        //alert(counter);
    }
    });

    var counter = function() {
    imagesArray[i].setOpacity(0.00);
    i++;
    if(i > 23){
        i = imagesArray.length - 23;
    }
    imagesArray[i].setOpacity(0.60);
    speed = parseInt(speed);
    setTimeout(counter, speed);
    document.getElementById("test").innerHTML = speed;
    };

    counter();

首先,我将尝试指出您的代码的一些问题在 onSlide 回调中,您有:

var timer = 0;
timer.length = 0;
timer = setTimeout(counter, value);
clearTimeout(timer);

因此,每次使用滑块时,您都将局部变量 timer 初始化为 0。您从不使用该值,因此这没有意义。事实上,这足以打破你的逻辑,但还有其他问题。然后,你尝试将timerlength 属性设置为0。这一定会导致运行时错误吗?号码没有length属性。然后,您将 timer 分配给 setTimeout() returns 的 id,这一切都很好,但是随后,您立即清除了超时,从而阻止了计划的 counter() 调用的执行。

另一方面,counter 函数使用 setTimeout 调用自身,但不会捕获返回的 ID,这意味着无论您在onSlide 回调。

然后我没有看到 speed 变量是在哪里定义或设置的。

基本上,您的代码存在太多问题,无法在答案范围内全部解决。一个合理的方法可能看起来像这样:

var timer, speed; //Global, or at least in a scope shared by both the onSlide callback and the counter function

$('input[type="range"]').rangeslider({
  ...
  onSlide: function() {
    clearTimeout(timer); //Cancel the currently pending execution of counter();
    speed = ... //Read value from slider
    timer = clearTimeout(counter, speed);
  },
  ...
});

var counter = function() {
  ...
  timer = setTimeout(counter, speed);
  ...
};

值得注意的是,使用这种方法,只要在超时之前调整滑块,counter() 就不会执行。