在受限制的函数中返回上次计算的结果

Returning the last computed result in a throttled function

提问人:Niels Koop 提问时间:8/25/2023 更新时间:8/25/2023 访问量:44

问:

我正在做一个基于下划线 _.throttle 函数的练习。我们的函数略有修改,因为如果函数仍在等待执行下一次调用,我们将返回上次计算的结果。我已经设法使油门功能正常工作,但是计算最后一个结果对我来说并不成功。_.throttle

我试过什么

在油门功能之前,我曾研究过记忆功能,我认为将两者结合起来是一个聪明的主意。我尝试了多种不同的方法来在函数中实现记忆代码,但我的测试一直失败。以下是我的 2 次尝试:_.throttle

_.throttle = function (func, wait) {
  let throttle = false;
  let cache = {};

  return function (...arguments) {
    const key = JSON.stringify(arguments);
    let result = func.apply(this, arguments);
    cache[key] = result;

    if (!throttle) {
      throttle = true;

      setTimeout(function () {
        throttle = false;
      }, wait);

      return result;
    } else {
      return cache[key];
    }
  };
};
_.throttle = function (func, wait) {
  let throttle = false;
  let cache = {};

  return function (...arguments) {
    const key = JSON.stringify(arguments);

    if (throttle) {
      return cache[key];
    }

    let result = func.apply(this, arguments);
    cache[key] = result;
    throttle = true;

    console.log(cache[key]);


    setTimeout(function () {
      throttle = false;
    }, wait);

    return result;
  };
};

我在找什么

基本上,如果尚未完成,我想返回最后的计算结果。传递的函数反转通过其参数传递的字符串。我已经尝试了上述代码的几种变体,以确定它是否不在错误的位置,因此得到了错误的值,但我找不到它工作的位置。我做错了什么?setTimeout_.throttlereturn cache[key]

提前致谢!

JavaScript 下划线 .js 记忆限制

评论

0赞 Peter Seliger 8/25/2023
实际上,下划线已经提供了 OP 所需的一切......_.throttle 通过其第 3 个可选参数允许对前缘和后缘调用进行非常具体的调用处理,并且还实现了 _.memoize。因此,似乎没有理由自己发明一些东西,因为可以很容易地创建具有 OP 特定修改行为的函数,例如......optionsconst fct = _.throttle(_.memoize(toBeMemoizedAndThrottledFct), 200)
0赞 Julian 8/26/2023
_.throttle开箱即用,无需使用选项或.请参阅源代码中的行:underscorejs.org/docs/modules/throttle.html_.memoizereturn result

答:

0赞 Niels Koop 8/25/2023 #1

找到了一种方法来做我想做的事,而不需要记忆。原来你只需要在之前初始化结果,然后保存结果。以下是我如何通过测试的代码:

_.throttle = function (func, wait) {
  let throttle = false;
  let result;

  return function (...arguments) {
    if (throttle) {
      return result;
    }

    result = func.apply(this, arguments);
    throttle = true;

    setTimeout(function () {
      throttle = false;
    }, wait);

    return result;
  };
};

上面的程序返回一个受限制的函数。当有多个后续调用时,调用将只返回上次计算的结果!这样可以优化程序的速度。

评论

0赞 Peter Seliger 8/25/2023
OP 如何设法对最后返回的结果以及所有其他返回的结果采取行动,以及如何区分它们?