首页 > 解决方案 > 如何在 x 秒结束之前停止函数返回新结果,如果调用过早返回先前的结果

问题描述

创建一个函数onceEvery(),允许每 x 毫秒调用一次函数。第一个结果能够返回,但该函数不会阻止它在冷却时间完成之前被调用,而是返回之前的结果。提前致谢!

onceEvery =  function (func, wait) {
//return function then can only return every * seconds
  let cooldown = false;
  let result;
  let previous;
  //if called again while cooldown = true, return previous result
  if (!cooldown) {
    result = func;
    previous = result;
    beginCoolDown();
    return result;
  } else {
    return previous;
  }
  
  function beginCoolDown () {
    cooldown  = true;
    setTimeout (function () {
      cooldown = false;
    }, wait);
   }
  }

标签: javascript

解决方案


为此,您可以在函数外部跟踪您提供的最后一个结果以及最后一次提供它的时间,然后在调用函数时使用它来决定是否更新该信息:

const minInterval = 5000;       // 5 seconds (for example)
let lastResult = null;          // Last result provided
let nextAvailable = Date.now(); // When the next can be provided
function onceEvery() {
    const now = Date.now();
    if (now < nextAvailable) {
        return lastResult;
    }
    lastResult = /*...calculate result...*/;
    nextAvailable = now + minInterval;
    return lastResult;
}

现场示例:

const minInterval = 5000;       // 5 seconds (for example)
let lastResult = null;          // Last result provided
let nextAvailable = Date.now(); // When the next can be provided
function onceEvery() {
    const now = Date.now();
    if (now < nextAvailable) {
        console.log(Date.now(), "Too soon, returning last value:", lastResult);
        return lastResult;
    }
    lastResult = (lastResult || 0) + 1;
    nextAvailable = now + minInterval;
    console.log(Date.now(), "Calculated new value:", lastResult);
    return lastResult;
}

// Call it every second or so
setInterval(onceEvery, 1000);


推荐阅读