200毫秒表示防抖函数的延迟时间
当连续触发事件时,只有在最后一次触发后的 200 毫秒内没有新的触发事件时,getCertNumByProvince 函数才会被调用。这可以有效防止函数被频繁调用,从而减少性能开销,适用于处理用户输入、窗口调整大小等频繁触发的事件。
第一种方法(空参数调用方法)
<script type="text/javascript">
var debounceTimer;
// 防抖函数定义
var updateFooterDebounced = customDebounce(updateFooter, 200);
function customDebounce(func, delay) {
return function() {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(func, delay);
};
}
$(function () {
updateFooterDebounced()
});
//后续用到 updateFooter() 方法时都替换为 updateFooterDebounced();
</script>
第二种方法(需要传递参数情况)(更灵活)
<script type="text/javascript">
var debounceTimer;
// 应用防抖函数
var debouncedGetCertNumByProvince = customDebounce(getCertNumByProvince, 200);
function customDebounce(func, delay) {
return function(...args) {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => func.apply(this, args), delay);
};
}
$(function () {
debouncedGetCertNumByProvince("001", "省中心");
});
//后续用到 getCertNumByProvince() 方法时都替换为 debouncedGetCertNumByProvince();
</script>