您好,欢迎来到汇意旅游网。
搜索
您的当前位置:首页javascript函数节流和防抖的应用场景介绍

javascript函数节流和防抖的应用场景介绍

来源:汇意旅游网

本篇文章给大家带来的内容是关于php变量作用域的用法介绍(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

throttle 节流

事件触发到结束后只执行一次。

应用场景

触发mousemove事件的时候, 如鼠标移动。

触发keyup事件的情况, 如搜索。

触发scroll事件的时候, 譬如鼠标向下滚动停止时触发加载数据。

coding

方法1 防抖

// function resizehandler(fn, delay){
// clearTimeout(fn.timer);
// fn.timer = setTimeout(() => {
// fn();
// }, delay);
// }
// window.onresize = () => resizehandler(fn, 1000);

方法2 闭包 防抖

function resizehandler(fn, delay){
 let timer = null;
 return function() {
 const context = this;
 const args=arguments;
 clearTimeout(timer);
 timer = setTimeout(() => {
 fn.apply(context,args);
 }, delay);
 }
 }
 window.onresize = resizehandler(fn, 1000);

debounce 防抖

事件出发后一定的事件内执行一次。

应用场景

window 变化触发resize事件是, 只执行一次。

电话号码输入的验证, 只需停止输入后进行一次。

coding

function resizehandler(fn, delay, duration) {
 let timer = null;
 let beginTime = +new Date();
 return function() {
 const context = this;
 const args = arguments;
 const currentTime = +new Date();
 timer && clearTimeout(timer);
 if ((currentTime - beginTime) >= duration) {
 fn.call(context, args);
 beginTime = currentTime;
 } else {
 timer = setTimeout(() => {
 fn.call(context, args)
 }, delay);
 }
 }
 }

 window.onresize = resizehandler(fn, 1000, 1000);

Copyright © 2019- hids.cn 版权所有 赣ICP备2024042780号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务