忽略特定时间的函数调用

我正在寻找所描述问题的最佳解决方案。

场景:有一个函数getData()每秒被调用一次。如果现在调用它,我想忽略对这个函数的任何调用,比如说 5 秒。

我们如何最好地在 javascript 中实现这一点。


慕容森
浏览 129回答 3
3回答

慕工程0101907

保存上次通话时间并检查是否超过 5 秒:var lastCall = 0;function getData() {    if (lastCall >= moment().subtract(5, 'mins').unix()) {        return;    }    lastCall = moment().unix();    /* rest of code */}

jeck猫

添加一个标志并在 5 秒后切换它,并在每个未被忽略的调用上:var shouldIgnore = false;function getData() {    if (shouldIgnore) {        return;    }    shouldIgnore = true;    setTimeout(() => {        shouldIgnore = false;    }, 5000);    /* rest of code */}

ABOUTYOU

有可能使用 setTimeout 你可以做到。我已经给出了一些实用程序的示例示例,以使其更简单。油门功能:const throttle = (fn, ms = 0) => {  let lastRunTime;  return function(...args) {    const currTime = +new Date();    if (!lastRunTime || currTime - lastRunTime > ms) {      lastRunTime = +new Date();      fn.apply(this, args);    }  };};如何使用它:(async function throttleEx() {  const logTill1Sec = throttle(log, 1 * 1000);  logTill1Sec("deepakt_1");  await new Promise(r => setTimeout(r, 500)); //2 sec virtual delay  logTill1Sec("deepak_t2");})();输出: Mr. deepakt_1你注意到了,即使我多次调用 logAfter5Sec。它执行最后一个。您可以编写相同的方式调用一次。const throttle = (fn, ms = 0) => {  let lastRunTime;  return function(...args) {    const currTime = +new Date();    if (!lastRunTime || currTime - lastRunTime > ms) {      lastRunTime = +new Date();      fn.apply(this, args);    }  };};(async function throttleEx() {  const logTill1Sec = throttle(log, 1 * 1000);  logTill1Sec("deepakt_1");  await new Promise(r => setTimeout(r, 500)); //2 sec virtual delay  logTill1Sec("deepak_t2");})();const debounce = (fn, ms = 0) => {  let timeoutId;  return function(...args) {    clearTimeout(timeoutId);    timeoutId = setTimeout(() => fn.apply(this, args), ms);  };};const dLog = debounce(log, 200); //ms timedLog("deepak11");dLog("deepak22");dLog("deepak33");function log(name) {  console.log(`Mr. ${name}`);}(async function() {  const logAfter5Sec = debounce(log, 1 * 1000);  logAfter5Sec("deepak");  await new Promise(r => setTimeout(r, 500)); //2 sec virtual delay  logAfter5Sec("deepak2");})();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript