手把手带你实现防抖、节流

防抖、节流函数

一、debounce防抖是什么?

debounce 函数在给定的时间间隔内只允许你提供的回调函数执行一次,以此降低它的执行频率。防抖函数(设定时间之后出结果,重复点击无效,如果重复点击,从点击的时刻,重新计算时间)。总的来说就是防抖函数指定时间内重复点击重新计算指定时间,只有最后一次是有效点击。

1.debounce函数

代码如下(示例):

/**
        * debounce 函数在给定的时间间隔内只允许你提供的回调函数执行一次,以此降低它的执行频率。
        * @method 防抖函数(设定时间之后出结果,重复点击无效,如果重复点击,从点击的时刻,重新计算时间)
        * @param func 目标函数
        * @param wait 延迟执行毫秒数
      */

const debounce = (func, wait) => {
    
    
    let _lastTime
    return function() {
    
    
        clearTimeout(_lastTime)
        _lastTime = setTimeout(() => {
    
    
            func.apply(this, arguments)
        }, wait)
    }
}

2.使用方式

代码如下(示例):html文件

<body>
    <div id="app">
    	<button onclick="fun()">防抖</button>
    </div>
</body>
<script>
	var fun = debounce(function (){
    
    
	    console.log(111)
	},1000)
</script>

代码如下(示例):vue中

<template>
    <div id="app">
    	<button @click="fun()">防抖</button>
    </div>
</template>
<script>
	export default {
    
    
		methods: {
    
    
			fun:debounce(function(){
    
    
				console.log(111)
			},1000)
		}
	}
</script>

二、throttle节流是什么?

节流函数(设定时间之内只能点击一次,点击后立即触发,重复点击无效,必须等到设定时间执行完才执行第二次)

1.throttle函数

代码如下(示例):

/**
    * @method 节流函数(设定时间之内只能点击一次,点击后立即触发,重复点击无效,必须等到设定时间执行完才执行第二次)	
    * @param func 函数
    * @param wait 延迟执行毫秒数
 */
const throttle = (func, wait) => {
    
    
    if (wait == null || wait == undefined) {
    
    
        wait = 3000
    }
    let _lastTime = null
    // 返回新的函数
    return function() {
    
    
        let _nowTime = +new Date()
        if (_nowTime - _lastTime > wait || !_lastTime) {
    
    
            func.apply(this, arguments) // 将this和参数传给原函数
            _lastTime = _nowTime
        }
    }
}

2.使用方式

提示:同debounce防抖函数使用方式一样

总结

本文仅为示例,实际应用可以封装到js文件中全局引入。如有错误欢迎评论区解答!

如果对您有所帮助,请留下您的大拇指吧!!

猜你喜欢

转载自blog.csdn.net/qq_44860866/article/details/126723415