Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit Punch card activity. Click here for details.
๐งจ Hi, I’m Smooth, a sophomore SCAU front er
๐ this article is when I review the anti-shake and throttling, I really understand their working principle through handwriting, so WRITE an article to record, I hope to help you
๐ if the article is wrong, please comment section correction, thank you!
Writing is not easy, thank you for your support!
preface
This article will take you from the basics to understanding how to write the immediate and non-immediate versions of the throttles.
Function debounce
Wait n seconds after the event is triggered before executing the callback (that is, the function you passed in), and if it is triggered again within n seconds, retry the timer.
Personal understanding
Function stabilization is when the mage sends a skill to read the bar, the skill will read the bar again, until the skill trigger (that is, n seconds not triggered).
example
<body> <input type="text" id='debounce' /> </body> <script> console.log(content) } let inputb = document.getElementById('debounce'); inputb.addEventListener('keyup', function (e) { ajax(e.target.value) }) </script>Copy the code
Take a look at the results:
As you can see, as soon as we press the keyboard, the keyboard input event is triggered. 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:
Add the following functions
Function debounce(fn, wait) {let timer; return function () { if (timer) clearTimeout(timer); // Each time, the timer is cleared and the count restarts, i.e., after not executing debounce for a period of wait, Timer = setTimeout(() => {fn.apply(this, arguments); }} let debounceAjax = debounce(ajax, 500, true); inputb.addEventListener('keyup', function (e) { debounceAjax(e.target.value) })Copy the code
Demo animation
As you can see, with the addition of anti-shake, when you type frequently, the function is not executed immediately, but only when you have no input within a specified interval. If you stop typing but enter it again within a specified interval, timing is retriggered.
Immediate execution version
That is, the first input directly executes the function once, and then starts to shake
Function debounce(fn, wait, immediate) {let timer; return function () { if (immediate) { immediate = ! immediate; // Take the anti-fn. apply(this, arguments); } if (timer) clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, arguments); }, wait) } }Copy the code
Demo animation
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.
Personal understanding
Function throttling is the rate of fire in an FPS game. Even if you hold down the mouse to shoot, the bullet will only be fired within the specified rate of fire, which is not as bad as your gun. It is like the difference between a sniper rifle and a machine gun.
If the timestamp interval is longer than wait, execute the function and then update the previous time
example
function throttle(fn, wait) { let prev = new Date(); return function () { const now = new Date(); if (now - prev > wait) { fn.apply(this, arguments); prev = now; // Throttle (Ajax, 2000); // Throttle (Ajax, 2000);Copy the code
Demo animation
As you can see, the Ajax will execute every 2 seconds as we type.
Immediate execution version
That is, the first input directly executes the function once, and then starts throttling again
DoNow === null; doNow = setTimeout; doNow = setTimeout; Wait until doNow is set to null to allow the function to execute
function throttle(fn, wait) { let doNow = null; return function () { if (! doNow) { fn.apply(this, arguments); doNow = setTimeout(() => { doNow = null; }, wait); }}}Copy the code
Demo animation
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
The last
I’m Smoothzjc, dedicated to producing more good articles than just the front end
You can also pay attention to my public account @smooth front-end growth record, timely through the mobile terminal to get the latest article news!
Writing is not easy, thanks for your support โค
Phase to recommend
React Hook: How to Learn React Hook in 2022
A rare Webpack study Guide (10,000 words to get you started with Webpack and master common advanced configuration)
A brief talk about Fiber through Iteration 15 through 17
The whole process from URL input to page display
“[Offer Harvester CSS Review series] Please explain what IS BFC? What are its application scenarios?”
Github + Hexo Implement your own personal blog, Configuration theme (super detailed)
10 minutes to thoroughly Understand how to configure subdomains to deploy multiple projects
This article explains how to configure pseudo static to solve the 404 problem of deployment project refresh page
Learn common horizontal and vertical Centered interview questions in 3 minutes
ใ Suggested collection ใ a summary of git common instructions!! Suitable for small white and want to understand the basic instructions of Git at work.
A brief introduction to javascript prototypes and prototype chains