gpt4 book ai didi

javascript - 取消去抖动功能

转载 作者:行者123 更新时间:2023-11-28 16:48:42 25 4
gpt4 key购买 nike

我有以下去抖函数,我需要能够通过在 debounce 函数范围内调用 clearTimeout(timeout); 来取消去抖。我不能为此使用库。

这是我的代码:

var utils = (function(){
return {
debounce: function(func, wait, immediate){
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
}
})();

我希望能够做这样的事情,但我又无法弄清楚。

var deb = utils.debounce(function(){ console.log("do something"); }, 500);

$(document).on('keyup', '#myId', deb);

deb.cancel(); //this cancel call clears the timeout variable in the debounce function.

最佳答案

将取消函数作为属性添加到返回的函数中:

const utils = (function(){
return {
debounce: function(func, wait, immediate) {
let timeout;
const fn = function() {
const context = this, args = arguments;
const later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
return Object.assign(fn, {
clear() { clearTimeout(timeout); }
});
}
}
})();

关于javascript - 取消去抖动功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60215981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com