性能优化之函数防抖

    技术2025-08-29  6

    所谓函数防抖就是让函数在触发时的n秒后执行,若函数被反复触发且触发间隔小于n秒,则函数会在最后一次触发时的n秒后执行一次

    使用场景:搜索框输入并实时显示结果、鼠标滑过不同的菜单发出相应的ajax请求等。

    举例

    (非立即执行版)当鼠标在蓝色div内移动时,div内的数字加1

    <style> .ab { height: 200px; background-color: blue; line-height: 200px; text-align: center; color: white; font-size: 60px; } </style> <div class="ab"></div> <script> function doSomething() { ab.innerHTML = ++count } function debounce(func, wait) { let timer return function () { clearTimeout(timer) timer = setTimeout(func, wait) } } let count = 0 let ab = document.querySelector('.ab') ab.innerHTML=count ab.onmousemove = debounce(doSomething, 1000) </script>

    立即执行版

    <style> .ab { height: 200px; background-color: blue; line-height: 200px; text-align: center; color: white; font-size: 60px; } </style> <div class="ab"></div> <script> function doSomething() { ab.innerHTML = ++count } function debounce(func, wait) { let timer return function () { clearTimeout(timer) let callNow=!timer timer = setTimeout(()=>{ timer=null }, wait) if(callNow){ func() } } } let count = 0 let ab = document.querySelector('.ab') ab.innerHTML=count ab.onmousemove = debounce(doSomething, 1000) </script>

    获取this和event

    <style> .ab { height: 200px; background-color: blue; line-height: 200px; text-align: center; color: white; font-size: 60px; } </style> <div class="ab"></div> <script> function doSomething() { ab.innerHTML = ++count } function debounce(func, wait) { let timer return function () { let self=this let args=arguments clearTimeout(timer) timer = setTimeout(func.call(self,args), wait) } } //或者使用箭头函数也能获取调用对象的this //timer = setTimeout(()=>{ // func() // }, wait) let count = 0 let ab = document.querySelector('.ab') ab.innerHTML=count ab.onmousemove = debounce(doSomething, 1000) </script>
    Processed: 0.021, SQL: 9