René's URL Explorer Experiment


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

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@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-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:afbad3c3-9021-7c76-cd46-5b46bf160792
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-id9320:21A1BD:CD409:11EB22:696A686B
html-safe-nonce7637109b0986d21ea58e080f899dc977c4844d0d50cad4d113473d988bdfeb42
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5MzIwOjIxQTFCRDpDRDQwOToxMUVCMjI6Njk2QTY4NkIiLCJ2aXNpdG9yX2lkIjoiNzI1MTU0NTMwMzEyNDk2MTM4NyIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac6f59f685447b37875625410bfc43d7976016749da507c80eb6c6185c11aee2f1
hovercard-subject-tagissue:679773058
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/sisterAn/JavaScript-Algorithms/95/issue_layout
twitter:imagehttps://opengraph.githubassets.com/9865b53a81e998a6c38ded0f177b76ea886ef943c5eb08d5f8216d1ace720a7c/sisterAn/JavaScript-Algorithms/issues/95
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/9865b53a81e998a6c38ded0f177b76ea886ef943c5eb08d5f8216d1ace720a7c/sisterAn/JavaScript-Algorithms/issues/95
og:image:alt我们上周 手写了一个节流函数throttle ,这周我们继续手写手写一个防抖函数 debounce 手写一个 debounce 防抖函数 debounce 指的是某个函数在某段时间内,无论触发了多少次回调,都只执行最后一次 实现原理就是利用定时器,函数第一次执行时设定一个定时器,之后调用时发现已经设定过定时器就清空之前的定时器,并重新设定一个新的定时器,如果存在没有被清空的定时器,当定时器计...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamesisterAn
hostnamegithub.com
expected-hostnamegithub.com
None6fea32d5b7276b841b7a803796d9715bc6cfb31ed549fdf9de2948ac25d12ba6
turbo-cache-controlno-preview
go-importgithub.com/sisterAn/JavaScript-Algorithms git https://github.com/sisterAn/JavaScript-Algorithms.git
octolytics-dimension-user_id19721451
octolytics-dimension-user_loginsisterAn
octolytics-dimension-repository_id252061924
octolytics-dimension-repository_nwosisterAn/JavaScript-Algorithms
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id252061924
octolytics-dimension-repository_network_root_nwosisterAn/JavaScript-Algorithms
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
releasef2d9f6432a5a115ec709295ae70623f33bb80aee
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/sisterAn/JavaScript-Algorithms/issues/95#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2FsisterAn%2FJavaScript-Algorithms%2Fissues%2F95
GitHub CopilotWrite better code with AIhttps://github.com/features/copilot
GitHub SparkBuild and deploy intelligent appshttps://github.com/features/spark
GitHub ModelsManage and compare promptshttps://github.com/features/models
MCP RegistryNewIntegrate external toolshttps://github.com/mcp
ActionsAutomate any workflowhttps://github.com/features/actions
CodespacesInstant dev environmentshttps://github.com/features/codespaces
IssuesPlan and track workhttps://github.com/features/issues
Code ReviewManage code changeshttps://github.com/features/code-review
GitHub Advanced SecurityFind and fix vulnerabilitieshttps://github.com/security/advanced-security
Code securitySecure your code as you buildhttps://github.com/security/advanced-security/code-security
Secret protectionStop leaks before they starthttps://github.com/security/advanced-security/secret-protection
Why GitHubhttps://github.com/why-github
Documentationhttps://docs.github.com
Bloghttps://github.blog
Changeloghttps://github.blog/changelog
Marketplacehttps://github.com/marketplace
View all featureshttps://github.com/features
Enterpriseshttps://github.com/enterprise
Small and medium teamshttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
App Modernizationhttps://github.com/solutions/use-case/app-modernization
DevSecOpshttps://github.com/solutions/use-case/devsecops
DevOpshttps://github.com/solutions/use-case/devops
CI/CDhttps://github.com/solutions/use-case/ci-cd
View all use caseshttps://github.com/solutions/use-case
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
View all industrieshttps://github.com/solutions/industry
View all solutionshttps://github.com/solutions
AIhttps://github.com/resources/articles?topic=ai
Software Developmenthttps://github.com/resources/articles?topic=software-development
DevOpshttps://github.com/resources/articles?topic=devops
Securityhttps://github.com/resources/articles?topic=security
View all topicshttps://github.com/resources/articles
Customer storieshttps://github.com/customer-stories
Events & webinarshttps://github.com/resources/events
Ebooks & reportshttps://github.com/resources/whitepapers
Business insightshttps://github.com/solutions/executive-insights
GitHub Skillshttps://skills.github.com
Documentationhttps://docs.github.com
Customer supporthttps://support.github.com
Community forumhttps://github.com/orgs/community/discussions
Trust centerhttps://github.com/trust-center
Partnershttps://github.com/partners
GitHub SponsorsFund open source developershttps://github.com/sponsors
Security Labhttps://securitylab.github.com
Maintainer Communityhttps://maintainers.github.com
Acceleratorhttps://github.com/accelerator
Archive Programhttps://archiveprogram.github.com
Topicshttps://github.com/topics
Trendinghttps://github.com/trending
Collectionshttps://github.com/collections
Enterprise platformAI-powered developer platformhttps://github.com/enterprise
GitHub Advanced SecurityEnterprise-grade security featureshttps://github.com/security/advanced-security
Copilot for BusinessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/premium-support
Pricinghttps://github.com/pricing
Search syntax tipshttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
documentationhttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2FsisterAn%2FJavaScript-Algorithms%2Fissues%2F95
Sign up https://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=sisterAn%2FJavaScript-Algorithms
Reloadhttps://github.com/sisterAn/JavaScript-Algorithms/issues/95
Reloadhttps://github.com/sisterAn/JavaScript-Algorithms/issues/95
Reloadhttps://github.com/sisterAn/JavaScript-Algorithms/issues/95
sisterAn https://github.com/sisterAn
JavaScript-Algorithmshttps://github.com/sisterAn/JavaScript-Algorithms
Notifications https://github.com/login?return_to=%2FsisterAn%2FJavaScript-Algorithms
Fork 649 https://github.com/login?return_to=%2FsisterAn%2FJavaScript-Algorithms
Star 5.7k https://github.com/login?return_to=%2FsisterAn%2FJavaScript-Algorithms
Code https://github.com/sisterAn/JavaScript-Algorithms
Issues 158 https://github.com/sisterAn/JavaScript-Algorithms/issues
Pull requests 0 https://github.com/sisterAn/JavaScript-Algorithms/pulls
Actions https://github.com/sisterAn/JavaScript-Algorithms/actions
Projects 0 https://github.com/sisterAn/JavaScript-Algorithms/projects
Security Uh oh! There was an error while loading. Please reload this page. https://github.com/sisterAn/JavaScript-Algorithms/security
Please reload this pagehttps://github.com/sisterAn/JavaScript-Algorithms/issues/95
Insights https://github.com/sisterAn/JavaScript-Algorithms/pulse
Code https://github.com/sisterAn/JavaScript-Algorithms
Issues https://github.com/sisterAn/JavaScript-Algorithms/issues
Pull requests https://github.com/sisterAn/JavaScript-Algorithms/pulls
Actions https://github.com/sisterAn/JavaScript-Algorithms/actions
Projects https://github.com/sisterAn/JavaScript-Algorithms/projects
Security https://github.com/sisterAn/JavaScript-Algorithms/security
Insights https://github.com/sisterAn/JavaScript-Algorithms/pulse
New issuehttps://github.com/login?return_to=https://github.com/sisterAn/JavaScript-Algorithms/issues/95
New issuehttps://github.com/login?return_to=https://github.com/sisterAn/JavaScript-Algorithms/issues/95
手写一个防抖函数 debouncehttps://github.com/sisterAn/JavaScript-Algorithms/issues/95#top
手写源码https://github.com/sisterAn/JavaScript-Algorithms/issues?q=state%3Aopen%20label%3A%22%E6%89%8B%E5%86%99%E6%BA%90%E7%A0%81%22
https://github.com/sisterAn
https://github.com/sisterAn
sisterAnhttps://github.com/sisterAn
on Aug 16, 2020https://github.com/sisterAn/JavaScript-Algorithms/issues/95#issue-679773058
手写了一个节流函数throttlehttps://github.com/sisterAn/JavaScript-Algorithms/issues/92
underscore 1.9.1https://github.com/jashkenas/underscore/tree/1.9.1
深入浅出防抖函数 debouncehttps://muyiy.cn/blog/7/7.2.html
前端面试题——自己实现debouncehttps://zhuanlan.zhihu.com/p/86426949
手写源码https://github.com/sisterAn/JavaScript-Algorithms/issues?q=state%3Aopen%20label%3A%22%E6%89%8B%E5%86%99%E6%BA%90%E7%A0%81%22
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.