" />

小言_互联网的博客

前端基础:防抖与节流

452人阅读  评论(0)

一、一种现象

有一个input框,每次输入都要触发一次change事件,其实这大可不必,比如我输入 “上海” 两个字,竟然触发了9次。


  
  1. <body>
  2. <input type="text" />
  3. <script src="./t.js"> </script>
  4. </body>

  
  1. const input = document. querySelector( 'input')
  2. input. oninput = function( ) {
  3. console. log( this. value)
  4. }

 假如每次change都会和后端发生一次交互,这个性能就会很惨。

怎么才能让这个次数变的少?

二、防抖

用户触发事件过于频繁,只要最后一次事件的操作。比如我们可以设置500ms,只要在500ms内你一直还在输入,也就是说你的停顿是少于500ms的,那么就不触发change事件里的复杂逻辑。在执行复杂逻辑之前就把定时器清理掉。


  
  1. const input = document. querySelector( 'input')
  2. let t = null
  3. input. oninput = function( ) {
  4. if (t !== null) {
  5. clearTimeout(t)
  6. }
  7. t = setTimeout( () => {
  8. // 用一句打印代替复杂的业务逻辑
  9. console. log( this. value)
  10. }, 500)
  11. }

三、代码改进

上面的代码有2个大毛病:

  1. let t是个全局变量;
  2. 防抖的逻辑 if (t !== null) 和 业务逻辑都混在一起了。

用闭包来改进这段代码

上面,在调用debounce的时候,第一个参数是传递一个函数,

我们传的是一个() => {console.log(this.value)} ,这里的this是window,但是我们想要的是input。

所以,可以用call的方式来


  
  1. const input = document. querySelector( 'input')
  2. input. oninput = debounce( function( ) { // 这里如果用箭头函数,还是指向window,不能用箭头函数
  3. // 业务逻辑,用一个打印代替
  4. console. log( this. value)
  5. }, 500)
  6. function debounce( fn, delay) {
  7. let t = null
  8. return function( ) {
  9. if (t !== null) {
  10. clearTimeout(t)
  11. }
  12. t = setTimeout( () => {
  13. // 执行业务逻辑,这里的this就是input 事件对象
  14. console. log( 'this: ', this)
  15. fn. call( this)
  16. }, delay)
  17. }
  18. }

四、节流

有一种情形,滚动事件,会执行很多次。


  
  1. window. onscroll = function( ) {
  2. console. log( '---------')
  3. }

 你看,不到一秒钟随便滚动一下就是100多次。

防抖:只执行最后一次;

节流:控制执行次数;让耗性能的方法减少执行次数;

和防抖是一样的写法


  
  1. window. onscroll = throttle( () => {
  2. // 这里是业务逻辑,this:window
  3. console. log( '..........')
  4. }, 500)
  5. function throttle( fn, delay) {
  6. let flag = true
  7. return function( ) {
  8. if (flag) {
  9. setTimeout( () => {
  10. fn. call( this)
  11. flag = true
  12. }, delay)
  13. }
  14. flag = false
  15. }
  16. }

 


转载:https://blog.csdn.net/GY_U_YG/article/details/125492220
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场