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");})();