Take you hand in hand to achieve anti-shake and throttling

Anti-shake, throttling function

1. What is debounce anti-shake?

The debounce function allows the callback function you provide to execute only once in a given interval, thereby reducing its execution frequency. Anti-shake function (the result will be displayed after the set time, repeated clicks are invalid, if repeated clicks, the time will be recalculated from the moment of click). In general, the anti-shake function repeatedly clicks within the specified time to recalculate the specified time, and only the last click is valid.

1. debounce function

The code is as follows (example):

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

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

2. How to use

The code is as follows (example): html file

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

The code is as follows (example): in vue

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

2. What is throttle?

Throttling function (you can only click once within the set time, and it will be triggered immediately after clicking. Repeated clicking is invalid, and you must wait until the set time is completed before executing the second time)

1.throttle function

The code is as follows (example):

/**
    * @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. How to use

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

Summarize

This article is just an example, and the actual application can be packaged into a js file and imported globally. If there are any mistakes, welcome to answer in the comment area!

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

Guess you like

Origin blog.csdn.net/qq_44860866/article/details/126723415