JavaScript 函数的防抖与节流

JavaScript 函数的防抖与节流

防抖和节流可以很好的解决在绑定一些事件(resize,scroll,mousemove )频繁触发的情况。

防抖和节流的区别

假设一个用户一直触发这个函数,且每次触发函数的间隔小于wait,防抖的情况下只会调用一次,而节流的情况会每隔一定时间(参数wait)调用函数。

实例分析

<!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>
</head>
<style>
	.fd{
		height:150px;
		width:150px;
		line-height:150px;
		text-align:center;
		color: #fff;
		background-color: #FFC0CB;
		font-size:80px;
	}
</style>
<body>

   <div  id="content" class="fd"></div>
   <script>
       let num = 1;
       let content = document.getElementById('content');
       function count() {
           content.innerHTML = num++;
       };
       content.onmousemove = count;
   </script>
</body>
</html>

在上述代码中,div 元素绑定了 mousemove 事件,当鼠标在 div区域中移动的时候会持续地去触发该事件导致频繁执行函数,这种情况我们就可以用防抖和节流来解决。

防抖(debounce)

防抖是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。

防抖函数分为非立即执行版和立即执行版。

非立即执行

非立即执行的意思是触发事件后函数不会立即执行,而是在 n 秒后执行,如果在 n 秒内又触发了事件,则会重新计算函数,直到触发结束再去执行时间。

<!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>
</head>
<style>
	.fd{
		height:150px;
		width:150px;
		line-height:150px;
		text-align:center;
		color: #fff;
		background-color: #FFC0CB;
		font-size:80px;
	}
</style>
<body>

   <div  id="content" class="fd"></div>
   <script>
       let num = 1;
       let content = document.getElementById('content');
       function count() {
           content.innerHTML = num++;
       };
       function debounce(nums, wait) {
           let timeout;
           return function () {
               let context = this;
               let args = arguments;
       
               if (timeout) clearTimeout(timeout);
               
               timeout = setTimeout(() => {
                   nums.apply(context, args)
               }, wait);
           }
       }
	   content.onmousemove = debounce(count,100);
   </script>
</body>
</html>
立即执行

立即执行是触发事件后函数会立即执行,然后 n 秒内不触发事件才能继续执行函数的效果。

function debounce(nums,wait) {
	       let timeout;
	       return function () {
	           let context = this;
	           let args = arguments;
	   
	           if (timeout) clearTimeout(timeout);
	   
	           let callNow = !timeout;
	           timeout = setTimeout(() => {
	               timeout = null;
	           }, wait)
	   
	           if (callNow) nums.apply(context, args)
	       }
	   }
二者整合

整合代码引入immediate值,用来判断是要立即执行还是要非立即执行。

function debounce(nums,wait,immediate) {
//immediate true 表立即执行,false 表非立即执行
    let timeout;

    return function () {
        let context = this;
        let args = arguments;

        if (timeout) clearTimeout(timeout);
        if (immediate) {
            var callNow = !timeout;
            timeout = setTimeout(() => {
                timeout = null;
            }, wait)
            if (callNow) func.apply(context, args)
        }
        else {
            timeout = setTimeout(function(){
                nums.apply(context, args)
            }, wait);
        }
    }
}

节流(throttle)

节流是每隔一段时间执行一次。节流会稀释函数的执行频率。

节流分时间戳版和定时器版。时间戳版和定时器版的节流函数的区别就是,时间戳版的函数触发是在时间段内开始的时候,而定时器版的函数触发是在时间段内结束的时候

时间戳

在持续触发事件的过程中,函数会立即执行,并且每 1s 执行一次

<body>

   <div  id="content" class="fd"></div>
   <script>
       let num = 1;
       let content = document.getElementById('content');
       function count() {
           content.innerHTML = num++;
       };
       function throttle(nums, wait) {
           let previous = 0;
           return function() {
               let now = Date.now();
               let context = this;
               let args = arguments;
               if (now - previous > wait) {
                   nums.apply(context, args);
                   previous = now;
               }
           }
       }
	   content.onmousemove = throttle(count,1000);
   </script>
</body>
</html>
定时器

在持续触发事件的过程中,函数不会立即执行,并且每 1s 执行一次,在停止触发事件后,函数还会再执行一次

function throttle(nums, wait) {
    let timeout;
    return function() {
        let context = this;
        let args = arguments;
        if (!timeout) {
            timeout = setTimeout(() => {
                timeout = null;
                nums.apply(context, args)
            }, wait)
        }

    }
}
二者整合

整合代码引入type值,用来判断是要立即执行还是要非立即执行。

function throttle(func, wait ,type) {
//type=1时是时间戳,type=2 是定时器
    if(type===1){
        let previous = 0;
    }else if(type===2){
        let timeout;
    }
    return function() {
        let context = this;
        let args = arguments;
        if(type===1){
            let now = Date.now();

            if (now - previous > wait) {
                func.apply(context, args);
                previous = now;
            }
        }else if(type===2){
            if (!timeout) {
                timeout = setTimeout(() => {
                    timeout = null;
                    func.apply(context, args)
                }, wait)
            }
        }
    }
}

参考于 https://www.jianshu.com/p/c8b86b09daf0

发布了102 篇原创文章 · 获赞 252 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/low666/article/details/104988792