javascript - 如何在 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);
}
}
解决方案
为此,您可以在函数外部跟踪您提供的最后一个结果以及最后一次提供它的时间,然后在调用函数时使用它来决定是否更新该信息:
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);
推荐阅读
- excel - 按活动列 vba 求和
- c# - 如何阻止关闭按钮关闭多个选项卡?带有关闭按钮的 C# TabControl
- javascript - 在不使用获取请求的情况下将文件加载到沙盒 iframe
- c# - 如何以两种方式绑定属性WPF
- java - 在java中的三个线程内发送数据,一个接一个
- forms - 谷歌表单输入的验证规则,以避免不同输入字段中的重复值?
- python - Python ArgumentParser 到 Influxdb-Client
- swift - WKWebView 不会显示我需要它的网页
- nest-device-access - 使用服务帐号访问 API
- google-sheets - 允许 Google 表格上的“创建新过滤器视图”功能,并保护某些列