美好乡村建设网站,安徽弘泰建设管理有限公司网站,网站制作公司 恶意,深圳制作软件某些事件中(如 onresize onscroll onkeydown onkeyup onmousemove …)#xff0c;会连续触发函数的执行#xff0c;如果函数执行一些耗时的操作(如请求数据…)#xff0c;会影响性能#xff0c;也有可能造成服务器压力。这时可以用 防抖函数 或 节流函数解决这种问题。
防…某些事件中(如 onresize onscroll onkeydown onkeyup onmousemove …)会连续触发函数的执行如果函数执行一些耗时的操作(如请求数据…)会影响性能也有可能造成服务器压力。这时可以用 防抖函数 或 节流函数解决这种问题。
防抖函数:
不管事件怎么连接触发函数的执行我只在事件结束后的N毫秒执行一次函数如果事件还在连接触发就不执行函数。
!DOCTYPE html
html
headtitle/titlemeta charsetutf-8 /style typetext/css#box{width:200px;height:200px;border: 1px solid red;}/style
/head
bodydiv idbox/div/body
script
function debounce(fn,wait){let timeoutId null;return function(){let args arguments;timeoutId clearTimeout(timeoutId);timeoutId setTimeout(function(){fn(args);},wait)}
}
function doing(arg){console.log(arg);
}
let fn debounce(doing,1000);
box document.getElementById(box);
box.onmousemove function(){fn(1,2,3);
}
/script
/html
效果图 节流函数:
事件在连接触发的过程中我会隔N毫秒执行一次函数如果N毫秒内多次触发事件则只会执行一次函数。
!DOCTYPE html
html
headtitle/titlemeta charsetutf-8 /style typetext/css#box{width:200px;height:200px;border: 1px solid red;}/style
/head
bodydiv idbox/div/body
script
function throttle(fn,wait){let timeoutId null;return function(){let args arguments;let now Date.now();if(!timeoutId){timeoutId setTimeout(function(){timeoutId null;fn(args);},wait)}}
}function doing(arg){console.log(arg);
}
let fn throttle(doing,1000);
box document.getElementById(box);
box.onmousemovefunction(){fn(1,2,3);
}
/script
/html
效果图 自己体会一下 防抖函数 和 节流函数 的区别吧。 可以根据 效果图 体会体会。 体会不明白的自己去写一下运行试试了。
防抖函数的应用场景建议百度一下。懒得写。 节流函数的应用场景建议百度一下。懒得写。
---- 结束 ---- 仅学习。