使用setTimeout调用函数,并提供可选的停止方式

Calling function with setTimeout with optional way to stop one

本文关键字:方式 调用 setTimeout 函数 使用      更新时间:2023-09-26

我有一个函数,它运行一个回调数学计算。我使用这个函数对多个事物进行计算,方法是在前一个调用可能仍在处理时多次调用它。(我使用setTimeout来做计算)。

问题是,有时,我需要取消一个过早运行的函数。

For example…用户在画布上单击一个对象,画布就会自动放大并移动到该对象上。但用户可以鼠标滚轮到cancel缩放自动化,而平移仍然在进行,我希望这是有意义的,可以理解为什么我可能需要取消一个行动,而不是另一个。

这是我的代码设置:

var maths = new function() {
  var self = this;
  self.process = function(start, target, duration, callback) {
    var vector = (target - start) / duration;
    var startTime = Date.now();
    function update() {
      start += vector * (Date.now() - startTime);
      startTime = Date.now();
      if (start < target) {
        self.timer = setTimeout(update, 0);
      }
      callback(start);
    }
    update();
  }
};
maths.process(0, 10, 5000, function(value) {
  console.log('Run 1:' + value);
});
maths.process(-5, -1, 5000, function(value) {
  console.log('Run 2: ' + value);
});

所以我想知道,我如何能够在这里获得一种方法来取消一个特定的功能运行时,我需要,如果我需要。

我很难想出一个简单的方法来管理它,所以很容易取消任何一个电话。

我猜你想要的可以这样完成(虽然老实说,我不确定我理解你的正确:-):

var maths = new function() {
  var self = this;
  self.process = function(start, target, duration, callback) {
    var vector = (target - start) / duration;
    var startTime = Date.now();
    var didCancel = false;
    function update() {
      if(didCancel) {
        return;
      }
      start += vector * (Date.now() - startTime);
      startTime = Date.now();
      if (start < target) {
        self.timer = setTimeout(update, 0);
      }
      callback(start);
    }
    update();
    return {cancel: function() {didCancel = true;}};
  }
};
var prc1 = maths.process(0, 10, 5000, function(value) {
  console.log('Run 1:' + value);
});
var prc2 = maths.process(-5, -1, 5000, function(value) {
  console.log('Run 2: ' + value);
});
setTimeout(prc1.cancel, 500);