赞
踩
防抖(debounce):每次触发定时器后,取消上一个定时器,然后重新触发定时器。防抖一般用于用户未知行为的优化,比如搜索框输入弹窗提示,因为用户接下来要输入的内容都是未知的,所以每次用户输入就弹窗是没有意义的,需要等到用户输入完毕后再进行弹窗提示。
节流(throttle):每次触发定时器后,直到这个定时器结束之前无法再次触发。一般用于可预知的用户行为的优化,比如为scroll事件的回调函数添加定时器。
防抖:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <button id="btn">clickMe</button>
- </body>
- <script>
- let btn = document.getElementById('btn')
- function debounce(fn,delay=200){
- let timer = null
- return function(...args){
- if(timer){
- clearTimeout(timer)
- timer = null
- }
- timer = setTimeout(()=>{
- fn.apply(this,args)
- clearTimeout(timer)
- timer = null
- },delay)
- }
- }
- btn.addEventListener('click', debounce((e) => {
- console.log(e.target)
- }, 1000))
- </script>
- </html>
节流:
- <!DOCTYPE html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
-
- <body>
- <button id="btn">clickMe</button>
- </body>
- <script>
- let btn = document.getElementById('btn')
- function throttle(fn,delay=200){
- let flag = true
- return function(...args){
- if(!flag){
- return
- }
- flag = false
- setTimeout(()=>{
- fn.apply(this,args)
- flag = true
- },delay)
- }
- }
- btn.addEventListener('click', throttle((e) => {
- console.log(1)
- }, 1000))
- </script>
- </html>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。