多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] # 简介 当事件被触发时,设定一个周期延迟执行动作,若期间又被触发,则重新设定周期,直到周期结束,执行动作。 ![](https://box.kancloud.cn/5aa82c5e25e95846b27e3ebe0dfac9b5_1442x734.png) <br> 为此,我们举个示例代码来了解事件如何频繁的触发: 我们写个`index.html`文件: ~~~html <!DOCTYPE html> <html lang="zh-cmn-Hans"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="IE=edge, chrome=1"> <title>debounce</title> <style> #container{ width: 100%; height: 200px; line-height: 200px; text-align: center; color: #fff; background-color: #444; font-size: 30px; } </style> </head> <body> <div id="container"></div> <script src="debounce.js"></script> </body> </html> ~~~ `debounce.js`文件的代码如下: ~~~js var count = 1; var container = document.getElementById('container'); function getUserAction() { container.innerHTML = count++; }; container.onmousemove = getUserAction; ~~~ # 基本功能 ~~~ function debounce1(func, wait) { var timmer return function () { clearTimeout(timmer) timmer = setTimeout(func, wait) } } ~~~ <br> <br> # this 丢失修复 如果我们在`getUserAction`函数中`console.log(this)`,在不使用`debounce`函数的时候,`this`的值为: ~~~html <div id="container"></div> ~~~ 但是如果使用我们的 debounce 函数,this 就会指向 Window 对象! 所以我们需要将 this 指向正确的对象。 ~~~ /** * 修复 debounce1 中 func 中的 this 会指向 window */ function debounce2(func, wait) { var timmer return function () { var that = this // 获取this clearTimeout(timmer) timmer = setTimeout(function () { func.apply(that) //修复 this }, wait) } } ~~~ # event 对象 JavaScript 在事件处理函数中会提供事件对象 event,我们修改下 getUserAction 函数: ~~~js function getUserAction(e) { console.log(e); container.innerHTML = count++; }; ~~~ 如果我们不使用 debouce 函数,这里会打印 MouseEvent 对象 ![](https://box.kancloud.cn/74bbcf3786b957e98455e032dc25b451_1214x66.png) <br> 但是在我们实现的 debounce 函数中,却只会打印 undefined。修复代码如下 ~~~ /** * 修复 event 对象指向问题 */ function debounce3(func, wait) { var timmer return function () { var that = this var args = arguments clearTimeout(timmer) timmer = setTimeout(function () { func.apply(that, args) }, wait) } } ~~~ ## 传参 当要执行的函数需要额外传参时,要注意函数的this已丢失,需要重新绑定 ~~~ // function getUserAction(event) { // console.log(this) // DOM // console.log(event) // container.innerHTML = count++ // return false // } function getUserAction(...args) { console.log(this) // window console.log(args) // [mouseEvent, 1, 2] container.innerHTML = count++ return false } var setUseAction = debounce(function (event) { console.log(this) // DOM // 重新绑定this // getUserAction.call(this, event, 1, 2) getUserAction(event, 1, 2) }, 500, false) container.onmousemove = setUseAction ~~~ <br> <br> # 立刻执行 有时候我们不希望非要等到事件停止触发后才执行,而是立刻执行函数,然后等到停止触发 n 秒后,才可以重新触发执行。 ![](https://box.kancloud.cn/ea6e24a777ba1487f5ad63aa170cc237_2020x992.png) <br> 可以加个 immediate 参数判断是否是立刻执行。 ~~~ function debounce4(func, wait, immediate) { var timeout return function () { var context = this var args = arguments if (timeout) clearTimeout(timeout) if (immediate) { // 如果已经执行过,不再执行 var callNow = !timeout timeout = setTimeout(function () { timeout = null }, wait) if (callNow) func.apply(context, args) } else { timeout = setTimeout(function () { func.apply(context, args) }, wait) } } } ~~~ <br> <br> # 返回值 此时注意一点,就是 getUserAction 函数可能是有返回值的,所以我们也要返回函数的执行结果,但是当 immediate 为 false 的时候,因为使用了 setTimeout ,我们将 func.apply(context, args) 的返回值赋给变量,最后再 return 的时候,值将会一直是 undefined,所以我们只在 immediate 为 true 的时候返回函数的执行结果。 ~~~ /** * 返回 func 的返回值 */ function debounce5(func, wait, immediate) { var timeout, result return function () { var context = this var args = arguments if (timeout) clearTimeout(timeout); if (immediate) { var callNow = !timeout timeout = setTimeout(function () { timeout = null }, wait) // 在 immediate 为 true 的时候返回函数的执行结果 if (callNow) result = func.apply(context, args) } else { timeout = setTimeout(function () { func.apply(context, args) }, wait) } return result } } ~~~ <br> <br> # 取消 我们希望能取消 debounce 函数。比如说 debounce 的时间间隔是 10 秒钟,immediate 为 true,这样的话,只有等 10 秒后才能重新触发事件。而我们添加一个按钮,点击后能够取消防抖,立刻就能出发事件。 ~~~ function debounce(func, wait, immediate) { var timeout, result var debounced = function () { var context = this var args = arguments if (timeout) clearTimeout(timeout) if (immediate) { var callNow = !timeout timeout = setTimeout(function () { timeout = null }, wait) if (callNow) result = func.apply(context, args) } else { timeout = setTimeout(function () { func.apply(context, args) }, wait); } return result } // 取消 debounced.cancel = function () { clearTimeout(timeout) timeout = null } return debounced } ~~~ 同时修改demo代码 ~~~ var count = 1; var container = document.getElementById('container'); function getUserAction(e) { container.innerHTML = count++; }; var setUseAction = debounce(getUserAction, 10000, true); container.onmousemove = setUseAction; document.getElementById("button").addEventListener('click', function(){ setUseAction.cancel(); }) ~~~ <br> <br> # 参考资料 [JavaScript专题之跟着underscore学防抖](https://github.com/mqyqingfeng/Blog/issues/22)