javascript函数节流与防抖的应用场景介绍
发表时间:2025-11-11 来源:浏览器大全整理相关软件相关文章人气:
网页的本质就是超级文本标记语言,通过结合使用其他的Web技术(如:脚本语言、公共网关接口、组件等),可以创造出功能强大的网页。因而,超级文本标记语言是万维网(Web)编程的基础,也就是说万维网是建立在超文本基础之上的。超级文本标记语言之所以称为超文本标记语言,是因为文本中包含了所谓“超级链接”点。
本篇文章给大家带来的内容是关于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);以上就是javascript函数节流和防抖的应用场景介绍的详细内容,更多请关注php中文网其它相关文章!
网站建设是一个广义的术语,涵盖了许多不同的技能和学科中所使用的生产和维护的网站。