【节流和防抖】
节流(throttle)
所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数
1 2
| 开发使用场景 – 小米轮播图点击效果、鼠标移动、页面尺寸缩放resize、滚动条滚动 就可以加节流 假如一张轮播图完成切换需要300ms, 不加节流效果,快速点击,则嗖嗖嗖的切换,加上节流效果,不管快速点击多少次,300ms时间内,只能切换一张图片。
|
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
| <style> div { width: 200px; height: 200px; background-color: #CCCCCC; line-height: 200px; text-align: center; font-size: 30px; } </style>
<body> <div>0</div> <script type="text/javascript"> let div = document.querySelector("div"); let i = 0;
function fun() { this.innerHTML = ++i; }
function throttle(fn, time) { let startTime = 0; return function() { let nowTime = +new Date(); if (nowTime - startTime >= time) { fun.bind(div)(); startTime = nowTime; } } } div.addEventListener("mousemove", throttle(fun, 1000)) </script>
|
节流小案例-页面打开,可以记录上一次的视频播放位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <script>
const video = document.querySelector('video') video.ontimeupdate = _.throttle(function() { localStorage.setItem("time", video.currentTime); }, 1000) video.onloadeddata = function() { video.currentTime = localStorage.getItem("time") || 0; } </script>
|
防抖(debounce)
所谓防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间
1 2 3
| 开发使用场景- 搜索框防抖 假设输入就可以发送请求,但是不能每次输入都去发送请求,输入比较快发送请求会比较多 我们设定一个时间,假如300ms, 当输入第一个字符时候,300ms后发送请求,但是在200ms的时候又输入了一个字符,则需要再等300ms 后发送请求
|
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
| <style> div { width: 200px; height: 200px; background-color: #CCCCCC; line-height: 200px; text-align: center; font-size: 30px; } </style>
<body> <div>0</div> <script type="text/javascript"> let div = document.querySelector("div"); let i = 0;
function fun() { this.innerHTML = ++i; }
function debounce(fn, time) { let timer = null; return function() { if (timer) clearTimeout(timer); timer = setTimeout(fun.bind(div), time) } } div.addEventListener("mousemove", debounce(fun, 1000)) </script>
|
1 2 3
| 节流和防抖的使用场景是? 节流: 鼠标移动,页面尺寸发生变化,滚动条滚动等开销比较大的情况下 防抖: 搜索框输入,设定每次输入完毕n秒后发送请求,如果期间还有输入,则从新计算时间
|
Storage接口