Concepts and Examples
Function debounce
The callback is executed n seconds after the event is triggered, and if it is triggered again within n seconds, the timer is reset.
Look at a 🌰 (chestnut) :
// Simulate an Ajax requestfunction ajax(content) {
console.log('ajax request ' + content)
}
let inputa = document.getElementById('unDebounce')
inputa.addEventListener('keyup'.function(e) {ajax(e.target.value)}) copy codeCopy the code
Take a look at the results:
As you can see, all we have to do is press the keyboard to trigger the Ajax request. Not only is it a wasteful behavior in terms of resources, but in practice, users will only request a complete output of characters. Let’s optimize it:
// Simulate an Ajax requestfunction ajax(content) {
console.log('ajax request ' + content)
}
function debounce(fun, delay) {
return function (args) {
let that = this
let _args = args
clearTimeout(fun.id)
fun.id = setTimeout(function () {
fun.call(that, _args)
}, delay)
}
}
let inputb = document.getElementById('debounce')
let debounceAjax = debounce(ajax, 500)
inputb.addEventListener('keyup'.function(e) {debounceAjax(e.target.value)}) copy codeCopy the code
Take a look at the results:
As you can see, with the addition of anti-shaking, the request will not be sent when you type frequently, and the function will only be executed when you have no input within a specified interval. If you stop typing but enter it again within a specified interval, timing is retriggered. Here’s another 🌰 :
let biu = function () {
console.log('biu biu biu',new Date().Format('HH:mm:ss'))}let boom = function () {
console.log('boom boom boom',new Date().Format('HH:mm:ss'))}setInterval(debounce(biu,500),1000)
setInterval(Debounce (boom,2000),1000) copies the codeCopy the code
Take a look at the results:
🌰 is a good explanation. If the function is executed within a time interval, the timing will be retriggered. Biu will be executed every 1s after the first 1.5s, while boom will not be executed once. Because it has a 2s interval and a 1s execution time, the timing is retriggered each time
Personal understanding function tremble is the master hair skills to read, read skills will not stop by skills will read.
Function throttle
Specifies that a function can fire only once per unit of time. If more than one function is fired in this unit of time, only one function will take effect.
Take a look 🌰 :
function throttle(fun, delay) {
let last, deferTimer
return function (args) {
let that = this
let _args = arguments
let now = +new Date()
if (last && now < last + delay) {
clearTimeout(deferTimer)
deferTimer = setTimeout(function () {
last = now
fun.apply(that, _args)
}, delay)
}else {
last = now
fun.apply(that,_args)
}
}
}
let throttleAjax = throttle(ajax, 1000)
let inputc = document.getElementById('throttle')
inputc.addEventListener('keyup'.function(e) {throttleAjax(e.target.value)}) copy codeCopy the code
Take a look at the results:
As you can see, as we keep typing, ajax will execute every 1s of the time we set.
Combined with just biubiubiu’s 🌰 :
let biubiu = function () {
console.log('biu biu biu', new Date().Format('HH:mm:ss'))}setInterval(Throttle (Biubiu,1000),10) copies the codeCopy the code
No matter how small the execution interval is, it is always executed once in 1s.
In my opinion, function throttling is the rate of fire in FPS games. Even if you hold down the mouse to shoot, you will only fire bullets within the specified rate of fire.
conclusion
- Function stabilization and function throttling both prevent frequent triggering at one time, but the two brothers work differently.
- Function stabilization is performed only once in a certain period of time, while function throttling is performed at intervals.
Combined with Application Scenarios
- debounce
- Search search association, the user in the continuous input value, use the anti – shake to save the request resources.
- Windows triggers resize. Resize the browser window repeatedly to trigger resize. Use stabilization to make it trigger only once
- throttle
- Click the mouse repeatedly to trigger the mousedown(trigger only once per unit of time)
- Listen for rolling events, such as whether to slide to the bottom to automatically load more, and throttle
expand
Refer to the link: www.cnblogs.com/zichi/p/533…
This is classic code in elevation:
function throttle(method, context) {
clearTimeout(method.tId);
method.tId = setTimeout(function() { method.call(context); }, 100)} Copy codeCopy the code
As we know from the above example, this function should be debounce, not throttling, and many articles will use this code as an example. The function itself is correct, but the name is wrong.
The original author wrote this very well,
For example, with Throttle, you were assigned an assignment one day to learn more about throttle, and you were going to talk about it in class the next day. Zhang SAN heart is very happy, this concept in the classic book “JavaScript advanced programming” seen, open a look, two pages, and explain very clear, happy to do other things after reading. Li Si, however, felt that elevation 3 was a little short, so he googled other knowledge points about throttle, and was excited to see several ways to write throttle function. He found that elevation 3 was only the simplest way, and there were more ways to write with more elegant scenarios. Maybe he’d figured out that There was a Debounce at the same time as Throttle. What the hell was that? Anyway, the teacher did not say, later see, so contentedly to play the game. And Wang Wu, like Li Si, found Debounce. What is it? Debounce is the same as Throttle in Elevation 3. Digging further, the throttle function in elevation 3 should actually be called Debounce, and by the end of the day, He had fully understood throttle and Debounce.