JS函数防抖和节流
当一段程序执行频率很高时,为了避免对用户体验的影响,需要对频率进行限制,应用函数防抖和节流。
函数防抖:对于短时间内连续触发的事件(如滚动事件),防抖的应用就是让某个时间期限(delay)内,事件处理函数只执行一次。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>防抖和节流</title> <style> .parent{ height: 1000px; } </style> </head> <body> <div class="parent"> <input id="msg" type="text"> <p id="msg_p"></p> </div> <script> //滚动事件处理函数 function showTop(){ var scroTop = document.body.scrollTop || document.documentElement.scrollTop console.log(scroTop) } //定义防抖函数 function debounce(fn,delay) { let timer = null return function(){ if(timer) clearTimeout(timer) timer = setTimeout(fn,delay) } } //滚动事件持续触发时,不会执行处理函数,间隔时间达到1s 后,才执行 window.onscroll = debounce(showTop,1000) // window.addEventListener('scroll',showTop) </script> </body> </html>
函数节流: 当滚动事件持续触发,事件处理函数会按照每间隔 1s 的时间,执行一次。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>防抖和节流</title> <style> .parent{ height: 1000px; } </style> </head> <body> <div class="parent"> <input id="msg" type="text"> <p id="msg_p"></p> </div> <script> //滚动事件处理函数 function showTop(){ var scroTop = document.body.scrollTop || document.documentElement.scrollTop console.log(scroTop) } //滚动事件持续触发时,不会执行处理函数,间隔时间达到1s 后,才执行 window.onscroll = throttle(showTop,1000) // window.addEventListener('scroll',showTop) // 定义节流函数 function throttle(fn,delay) { let val_flag = true return function() { if(!val_flag) { return false } val_flag = false setTimeout(() => { fn() val_flag = true }, delay); } } </script> </body> </html>