计时器和 onChange

Timer and onChange

我需要谨慎地 运行 goTo() 函数,因为它每次都会下载一个大图像,所以要跳过 意外的 更改,我' m 检查 值是否已更改 and 某个 时间是否已过去 (2000 毫秒)。

scrubber.onValueChanged = function (value) {
    var timer;
    if (gallery.getCurrentIndex() !== value) {
        console.log('value changed');
        clearTimeout(timer); console.log('timer reset');
    }
    timer = setTimeout(function() {
      console.log('updating...');
      gallery.goTo(value);
    }, 2000);
};

.. 这有效,但它 不会 跳过它应该的更改,它仍然 运行 是 goTo() 函数的所有值我已经从,到和介于两者之间。

timer 是局部变量。因此,每次调用该函数时,timer 都会被重置,而 clearTimeout(timer) 不会按预期工作。修复将 timer 变量移动到函数范围之外或使其成为全局变量。

var timer;
....
scrubber.onValueChanged = function (value) {
    if (gallery.getCurrentIndex() !== value) {
        console.log('value changed');
        clearTimeout(timer); console.log('timer reset');
        timer = setTimeout(function() {
          console.log('updating...');
          gallery.goTo(value);
        }, 2000);
    }

};