当前位置:网站首页>防抖debounce和节流throttle的使用
防抖debounce和节流throttle的使用
2022-07-17 00:09:00 【666-上上签】
防抖函数:在n秒内只执行最后一次(在触发某个事件后,在下一次触发之前,中间的间隔时间如果超过设置的时间才会发送请求,一直触发就不会发送请求)
应用场景:按钮提交事件,搜索功能,浏览器窗口缩放,表单验证,scroll事件滚动,resize事件
/**
* 防抖 (n秒内只执行最后一次)
* @param fn
* @param delay
* @return {Function}
* @private
*/
export function _debounce(fn, delay) {
var newDelay = delay || 500;
var timer;
return function () {
var args = arguments;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
timer = null;
fn.apply(this, args);
}, newDelay);
};
}节流函数:在n秒内只执行一次(如果持续触发某个事件,则每隔n秒执行一次)
应用场景:拖拽,鼠标移动的距离,监听scroll滚动事件
/**
* 节流 (每隔n秒执行一次)
* @param fn
* @param interval
* @return {Function}
* @private
*/
export function _throttle(fn, interval) {
var last;
var timer;
var newInterval = interval || 200;
return function () {
var th = this;
var args = arguments;
var now = +new Date();
if (last && now - last < newInterval) {
clearTimeout(timer);
timer = setTimeout(function () {
last = now;
fn.apply(th, args);
}, newInterval);
} else {
last = now;
fn.apply(th, args);
}
};
}使用:
// 点击确认提交支付订单
confirmSubmit () {
this._debounce(this.action, 1000)();
}
边栏推荐
猜你喜欢
随机推荐
03 BTC agreement
Basic use of promise
04 BTC implementation
Byte two side: what is pseudo sharing? How to avoid it?
欢迎进入Hensen_的博客目录(全站式导航)
Express project creation and its routing introduction
Common asynchronous sending code writing
Today's code farmer girl learned about nodejs and repl interactive interpreter
安全多方计算体系架构及应用思考
开源项目丨 Taier 1.1 版本正式发布,新增功能一览为快
知名啤酒百威布局NFT,试图揭开“蓄谋已久”的上链面纱?
通感一体化融合的研究及其挑战
IPFs file persistence operation
iPhone 各大机型设备号
NFT数字藏品平台有哪些?哪些平台值得珍藏?
金融学 杂项记录
nodejs-uuid
Namenode and secondarynamenode
typeorm mysql upsert操作
温州大学X袋鼠云:高等人才教育建设,如何做到“心中有数”









