Title: 手写一个防抖函数 debounce · Issue #95 · sisterAn/JavaScript-Algorithms · GitHub
Open Graph Title: 手写一个防抖函数 debounce · Issue #95 · sisterAn/JavaScript-Algorithms
X Title: 手写一个防抖函数 debounce · Issue #95 · sisterAn/JavaScript-Algorithms
Description: 我们上周 手写了一个节流函数throttle ,这周我们继续手写手写一个防抖函数 debounce 手写一个 debounce 防抖函数 debounce 指的是某个函数在某段时间内,无论触发了多少次回调,都只执行最后一次 实现原理就是利用定时器,函数第一次执行时设定一个定时器,之后调用时发现已经设定过定时器就清空之前的定时器,并重新设定一个新的定时器,如果存在没有被清空的定时器,当定时器计时结束后触发函数执行。 // fn 是需要防抖处理的函数 // wait 是时间...
Open Graph Description: 我们上周 手写了一个节流函数throttle ,这周我们继续手写手写一个防抖函数 debounce 手写一个 debounce 防抖函数 debounce 指的是某个函数在某段时间内,无论触发了多少次回调,都只执行最后一次 实现原理就是利用定时器,函数第一次执行时设定一个定时器,之后调用时发现已经设定过定时器就清空之前的定时器,并重新设定一个新的定时器,如果存在没有被清空的定时器,当定时器计...
X Description: 我们上周 手写了一个节流函数throttle ,这周我们继续手写手写一个防抖函数 debounce 手写一个 debounce 防抖函数 debounce 指的是某个函数在某段时间内,无论触发了多少次回调,都只执行最后一次 实现原理就是利用定时器,函数第一次执行时设定一个定时器,之后调用时发现已经设定过定时器就清空之前的定时器,并重新设定一个新的定时器,如果存在没有被清空的定时器,当定时器计...
Opengraph URL: https://github.com/sisterAn/JavaScript-Algorithms/issues/95
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"手写一个防抖函数 debounce","articleBody":"我们上周 [手写了一个节流函数throttle](https://github.com/sisterAn/JavaScript-Algorithms/issues/92) ,这周我们继续手写手写一个防抖函数 `debounce`\r\n\r\n### 手写一个 debounce\r\n\r\n防抖函数 `debounce` 指的是某个函数在某段时间内,无论触发了多少次回调,**都只执行最后一次**\r\n\r\n实现原理就是利用定时器,函数第一次执行时设定一个定时器,之后调用时发现已经设定过定时器就清空之前的定时器,并重新设定一个新的定时器,如果存在没有被清空的定时器,当定时器计时结束后触发函数执行。\r\n\r\n```js\r\n// fn 是需要防抖处理的函数\r\n// wait 是时间间隔\r\nfunction debounce(fn, wait = 50) {\r\n // 通过闭包缓存一个定时器 id\r\n let timer = null\r\n // 将 debounce 处理结果当作函数返回\r\n // 触发事件回调时执行这个返回函数\r\n return function(...args) {\r\n // this保存给context\r\n const context = this\r\n \t// 如果已经设定过定时器就清空上一次的定时器\r\n if (timer) clearTimeout(timer)\r\n \r\n \t// 开始设定一个新的定时器,定时器结束后执行传入的函数 fn\r\n timer = setTimeout(() =\u003e {\r\n fn.apply(context, args)\r\n }, wait)\r\n }\r\n}\r\n\r\n// DEMO\r\n// 执行 debounce 函数返回新函数\r\nconst betterFn = debounce(() =\u003e console.log('fn 防抖执行了'), 1000)\r\n// 停止滑动 1 秒后执行函数 () =\u003e console.log('fn 防抖执行了')\r\ndocument.addEventListener('scroll', betterFn)\r\n```\r\n\r\n不过 `underscore` 中的 `debounce` 还有第三个参数:`immediate` 。这个参数是做什么用的呢?\r\n\r\n\u003e 传参 **immediate** 为 true, **debounce**会在 **wait** 时间间隔的开始调用这个函数 。(注:并且在 wait 的时间之内,不会再次调用。)在类似不小心点了提交按钮两下而提交了两次的情况下很有用。\r\n\r\n把 `true` 传递给 `immediate` 参数,会让 `debounce` 在 `wait` 时间开始计算之前就触发函数(也就是没有任何延时就触发函数),而不是过了 `wait` 时间才触发函数,而且在 `wait` 时间内也不会触发(相当于把 `fn` 的执行锁住)。 如果不小心点了两次提交按钮,第二次提交就会不会执行。\r\n\r\n那我们根据 `immediate` 的值来决定如何执行 `fn` 。如果是 `immediate` 的情况下,我们立即执行 `fn` ,并在 `wait` 时间内锁住 `fn` 的执行, `wait` 时间之后再触发,才会重新执行 `fn` ,以此类推。\r\n\r\n```js\r\n// immediate 表示第一次是否立即执行\r\nfunction debounce(fn, wait = 50, immediate) {\r\n let timer = null\r\n return function(...args) {\r\n // this保存给context\r\n const context = this\r\n if (timer) clearTimeout(timer)\r\n \r\n \t// immediate 为 true 表示第一次触发后执行\r\n \t// timer 为空表示首次触发\r\n if (immediate \u0026\u0026 !timer) {\r\n fn.apply(context, args)\r\n }\r\n \t\r\n timer = setTimeout(() =\u003e {\r\n fn.apply(context, args)\r\n }, wait)\r\n }\r\n}\r\n\r\n// DEMO\r\n// 执行 debounce 函数返回新函数\r\nconst betterFn = debounce(() =\u003e console.log('fn 防抖执行了'), 1000, true)\r\n// 第一次触发 scroll 执行一次 fn,后续只有在停止滑动 1 秒后才执行函数 fn\r\ndocument.addEventListener('scroll', betterFn)\r\n```\r\n\r\n### underscore 源码解析\r\n\r\n看完了上文的基本版代码,感觉还是比较轻松的,现在来学习下 underscore 是如何实现 debounce 函数的,学习一下优秀的思想,直接上代码和注释,本源码解析依赖于 [underscore 1.9.1](https://github.com/jashkenas/underscore/tree/1.9.1) 版本实现。\r\n\r\n```js\r\n// 此处的三个参数上文都有解释\r\n_.debounce = function(func, wait, immediate) {\r\n // timeout 表示定时器\r\n // result 表示 func 执行返回值\r\n var timeout, result;\r\n\r\n // 定时器计时结束后\r\n // 1、清空计时器,使之不影响下次连续事件的触发\r\n // 2、触发执行 func\r\n var later = function(context, args) {\r\n timeout = null;\r\n // if (args) 判断是为了过滤立即触发的\r\n // 关联在于 _.delay 和 restArguments\r\n if (args) result = func.apply(context, args);\r\n };\r\n\r\n // 将 debounce 处理结果当作函数返回\r\n var debounced = restArguments(function(args) {\r\n if (timeout) clearTimeout(timeout);\r\n if (immediate) {\r\n // 第一次触发后会设置 timeout,\r\n // 根据 timeout 是否为空可以判断是否是首次触发\r\n var callNow = !timeout;\r\n timeout = setTimeout(later, wait);\r\n if (callNow) result = func.apply(this, args);\r\n } else {\r\n \t// 设置定时器\r\n timeout = _.delay(later, wait, this, args);\r\n }\r\n\r\n return result;\r\n });\r\n\r\n // 新增 手动取消\r\n debounced.cancel = function() {\r\n clearTimeout(timeout);\r\n timeout = null;\r\n };\r\n\r\n return debounced;\r\n};\r\n\r\n// 根据给定的毫秒 wait 延迟执行函数 func\r\n_.delay = restArguments(function(func, wait, args) {\r\n return setTimeout(function() {\r\n return func.apply(null, args);\r\n }, wait);\r\n});\r\n```\r\n\r\n相比上文的基本版实现,`underscore` 多了以下几点功能。\r\n\r\n- 1、函数 `func` 的执行结束后返回结果值 `result`\r\n- 2、定时器计时结束后清除 `timeout` ,使之不影响下次连续事件的触发\r\n- 3、新增了手动取消功能 `cancel`\r\n- 4、`immediate` 为 `true` 后只会在第一次触发时执行,频繁触发回调结束后不会再执行\r\n\r\n参考 \r\n- [深入浅出防抖函数 debounce](https://muyiy.cn/blog/7/7.2.html)\r\n- [前端面试题——自己实现debounce](https://zhuanlan.zhihu.com/p/86426949)","author":{"url":"https://github.com/sisterAn","@type":"Person","name":"sisterAn"},"datePublished":"2020-08-16T15:21:55.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":0},"url":"https://github.com/95/JavaScript-Algorithms/issues/95"}
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:afbad3c3-9021-7c76-cd46-5b46bf160792 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 9320:21A1BD:CD409:11EB22:696A686B |
| html-safe-nonce | 7637109b0986d21ea58e080f899dc977c4844d0d50cad4d113473d988bdfeb42 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5MzIwOjIxQTFCRDpDRDQwOToxMUVCMjI6Njk2QTY4NkIiLCJ2aXNpdG9yX2lkIjoiNzI1MTU0NTMwMzEyNDk2MTM4NyIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 6f59f685447b37875625410bfc43d7976016749da507c80eb6c6185c11aee2f1 |
| hovercard-subject-tag | issue:679773058 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/sisterAn/JavaScript-Algorithms/95/issue_layout |
| twitter:image | https://opengraph.githubassets.com/9865b53a81e998a6c38ded0f177b76ea886ef943c5eb08d5f8216d1ace720a7c/sisterAn/JavaScript-Algorithms/issues/95 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/9865b53a81e998a6c38ded0f177b76ea886ef943c5eb08d5f8216d1ace720a7c/sisterAn/JavaScript-Algorithms/issues/95 |
| og:image:alt | 我们上周 手写了一个节流函数throttle ,这周我们继续手写手写一个防抖函数 debounce 手写一个 debounce 防抖函数 debounce 指的是某个函数在某段时间内,无论触发了多少次回调,都只执行最后一次 实现原理就是利用定时器,函数第一次执行时设定一个定时器,之后调用时发现已经设定过定时器就清空之前的定时器,并重新设定一个新的定时器,如果存在没有被清空的定时器,当定时器计... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | sisterAn |
| hostname | github.com |
| expected-hostname | github.com |
| None | 6fea32d5b7276b841b7a803796d9715bc6cfb31ed549fdf9de2948ac25d12ba6 |
| turbo-cache-control | no-preview |
| go-import | github.com/sisterAn/JavaScript-Algorithms git https://github.com/sisterAn/JavaScript-Algorithms.git |
| octolytics-dimension-user_id | 19721451 |
| octolytics-dimension-user_login | sisterAn |
| octolytics-dimension-repository_id | 252061924 |
| octolytics-dimension-repository_nwo | sisterAn/JavaScript-Algorithms |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 252061924 |
| octolytics-dimension-repository_network_root_nwo | sisterAn/JavaScript-Algorithms |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | f2d9f6432a5a115ec709295ae70623f33bb80aee |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
Links:
Viewport: width=device-width