尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

JS 最常用的性能优化 防抖和节流

JS 最常用的性能优化 防抖和节流 JS 最常用的性能优化 防抖和节流先看个问题你在搜索框打字每打一个字就发一次请求 → 1 秒打 5 个字发 5 次请求 → 服务器压力大页面卡顿你滚动页面每滚动 1px 就执行一次代码 → 1 秒滚动 100px执行 100 次 → 浏览器累死页面掉帧核心痛点有些事件input、scroll、resize、mousemove触发频率极高如果每次触发都执行代码会严重浪费性能导致页面卡顿。防抖“等你停下来我再执行” 大部分面向后端请求的节流“每隔一段时间只执行一次” 大部分面向前端渲染的防抖事件触发后等待一段时间比如 300ms如果这段时间内没有再次触发才执行代码如果又触发了就重新计时。/** * 防抖函数 * param {Function} fn - 要执行的函数 * param {Number} delay - 等待时间毫秒 * returns {Function} - 防抖后的函数 */functiondebounce(fn,delay){lettimernull;// 存定时器的变量// 返回一个新函数returnfunction(...args){// 如果之前有定时器先清除重新计时if(timer)clearTimeout(timer);// 重新设置定时器等待 delay 毫秒后执行 fntimersetTimeout((){fn.apply(this,args);// 用 apply 保证 this 指向正确args 是参数},delay);};}真实场景搜索框实时搜索inputtypetextidsearchInputplaceholder输入搜索内容...script// 模拟搜索请求functionsearch(keyword){console.log(发送搜索请求,keyword);}// 用防抖包装搜索函数停止输入 300ms 后才发请求constdebouncedSearchdebounce(search,300);constinputdocument.getElementById(searchInput);input.addEventListener(input,function(e){debouncedSearch(e.target.value);// 调用防抖后的函数});// 防抖函数functiondebounce(fn,delay){lettimernull;returnfunction(...args){if(timer)clearTimeout(timer);timersetTimeout((){fn.apply(this,args);},delay);};}/script节流事件持续触发时每隔固定时间比如 200ms只执行一次代码不管中间触发了多少次。/** * 节流函数时间戳版 * param {Function} fn - 要执行的函数 * param {Number} interval - 间隔时间毫秒 * returns {Function} - 节流后的函数 */functionthrottle(fn,interval){letlastTime0;// 记录上次执行的时间returnfunction(...args){constnowTimeDate.now();// 当前时间// 如果当前时间 - 上次执行时间 间隔时间才执行if(nowTime-lastTimeinterval){fn.apply(this,args);lastTimenowTime;// 更新上次执行时间为当前时间}};}// 定时器functionthrottle(fn,interval){lettimernull;returnfunction(...args){// 如果没有定时器才设置if(!timer){timersetTimeout((){fn.apply(this,args);timernull;// 执行完后清空定时器允许下次执行},interval);}};}真实场景滚动页面显示位置divstyleheight:2000px;向下滚动试试.../divdividscrollPosstyleposition:fixed;top:10px;left:10px;/divscript// 显示滚动位置functionshowPos(){constposwindow.scrollY;document.getElementById(scrollPos).innerText滚动位置${pos}px;}// 用节流包装每隔 200ms 只执行一次constthrottledShowPosthrottle(showPos,200);window.addEventListener(scroll,throttledShowPos);// 节流函数functionthrottle(fn,interval){letlastTime0;returnfunction(...args){constnowTimeDate.now();if(nowTime-lastTimeinterval){fn.apply(this,args);lastTimenowTime;}};}/script
返回列表