上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* @param {Function} fn
* @param {number} t milliseconds
* @return {Function}
*/
var debounce = function(fn, t) {
return function(...args) {
}
};
/**
* const log = debounce(console.log, 100);
* log('Hello'); // cancelled
* log('Hello'); // cancelled
* log('Hello'); // Logged at t=100ms
*/
typescript 解法, 执行用时: 68 ms, 内存消耗: 42.4 MB, 提交时间: 2023-04-17 16:07:57
type F = (...p: any[]) => any
function debounce(fn: F, t: number): F {
let timer = null
return function(...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn(...args)
}, t)
}
}
/**
* const log = debounce(console.log, 100);
* log('Hello'); // cancelled
* log('Hello'); // cancelled
* log('Hello'); // Logged at t=100ms
*/
typescript 解法, 执行用时: 72 ms, 内存消耗: 42.4 MB, 提交时间: 2023-04-17 16:07:43
type F = (...p: unknown[]) => unknown
function debounce(fn: F, ms: number): F {
let timer: ReturnType<typeof setTimeout> | null
return function (this: unknown, ...args) {
if (timer != null) clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, args)
}, ms)
}
}
/**
* const log = debounce(console.log, 100);
* log('Hello'); // cancelled
* log('Hello'); // cancelled
* log('Hello'); // Logged at t=100ms
*/
javascript 解法, 执行用时: 60 ms, 内存消耗: 41 MB, 提交时间: 2023-04-17 16:06:39
/**
* @param {Function} fn
* @param {number} t milliseconds
* @return {Function}
*/
var debounce = function(fn, t) {
var timer = null;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(function(){
fn(...args);
},t);
}
};
/**
* const log = debounce(console.log, 100);
* log('Hello'); // cancelled
* log('Hello'); // cancelled
* log('Hello'); // Logged at t=100ms
*/