防抖和节流
|
共同点 |
区别 |
|
防抖debounce |
在事件被频繁触发时 |
只执行最后一次 |
input输入 |
节流throttle |
减少事件执行的次数 |
有规律的进行 |
拖拽,scroll |
防抖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <input type="text" name="input"> </body> <script type="text/javascript"> var input = document.querySelector("input"); input.addEventListener("keyup", debounce(function() { console.log(input.value + "取后台请求") },1000)) function debounce(fn,delay){ let timer = null; return function () { if (timer) clearTimeout(timer); timer = setTimeout(() => { fn.call(this,arguments); timer = null; },delay) } } </script> </html>
HTML
|
函数:
1 2 3 4 5 6 7 8 9 10
| function debounce(fn,delay){ let timer = null; return function () { if (timer) clearTimeout(timer); timer = setTimeout(() => { fn.call(this,arguments); timer = null; },delay) } }
JAVASCRIPT
|
节流
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> div { width: 200px; height: 200px; background: pink; } </style> </head> <body> <div draggable = "true"></div> </body> <script type="text/javascript"> var div = document.querySelector("div"); div.addEventListener("drag", throttle(function(e) { console.log(e.clientX,e.clientY) },500))
function throttle(fn, delay) { let timer = null; return function() { if(timer) return; timer = setTimeout(() => { fn.apply(this,arguments); timer = null; },delay) } } </script> </html>
HTML
|
函数:
1 2 3 4 5 6 7 8 9 10 11
| function throttle(fn, delay) { let timer = null; return function() { if(timer) return; timer = setTimeout(() => { fn.apply(this,arguments); timer = null; },delay) } }
JAVASCRIPT
|
call()
和apply()
不管是call 还是 apply 都改变了函数的 this 对象
参考文章:https://juejin.cn/post/6844904009308831751