Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize Anti-shaking and throttling in JavaScript

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you "how to achieve anti-shaking and cost-saving in JavaScript". The content is simple and clear. I hope it can help you solve your doubts. Let the editor lead you to study and learn this article "how to achieve anti-shaking and cost-saving in JavaScript".

Anti-shaking

The automatic door senses someone, opens the door, and starts the 5-second countdown. Within 5 seconds, another person approaches the door, the door senses the person, and the 5-second countdown begins again.

When the event is triggered, set a delay, and if the event is triggered again, reset the delay until the delay ends and perform the action (to prevent multiple triggers)

Above the web application

Statistics for changing page size

Statistics on the position of scrolling pages

Control of the number of requests entered continuously in the input box

At first, click the button, console.log ('pay money')

Click const btn = document.getElementById ('btn') function payMoney () {console.log (' pay money');} btn.addEventListener ('click', payMoney)

Define debounce

Const btn = document.getElementById ('btn') function payMoney () {console.log (' pay money');} function debounce (func) {/ / returns the function in the function and returns the function return function () {func ()}} btn.addEventListener ('click', debounce (payMoney)) only when clicked

Set delay

Const btn = document.getElementById ('btn') function payMoney () {console.log (' pay money');} function debounce (func, delay) {return function () {setTimeout (_ = > func (), delay)}} btn.addEventListener ('click', debounce (payMoney, 1000))

Clear delay: failed to execute

Reason

The contents of the return function will be executed each time you click.

The execution function of each click is independent and does not interfere with each other.

Because there is no connection between them, the clearance delay doesn't work here at all.

To make a connection between these independent execution functions, a scope chain (closure) is needed.

Const btn = document.getElementById ('btn') function payMoney () {console.log (' pay money');} function debounce (func, delay) {return function () {let timer clearInterval (timer) timer = setTimeout (_ = > func (), delay)}} btn.addEventListener ('click', debounce (payMoney, 1000))

Place timer around the return function, so that when you define the listening event, you define the timer variable.

Because of the scope chain, all independent execution functions can access this timer variable

And now this timer variable has only been created once. Is unique, we just keep delaying the assignment of timer.

Each cleanup delay clears the last defined delay, which is equivalent to multiple functions sharing the same external variable.

Const btn = document.getElementById ('btn') function payMoney () {console.log (' pay money');} function debounce (func, delay) {let timer return function () {clearInterval (timer) timer = setTimeout (_ = > func (), delay)}} btn.addEventListener ('click', debounce (payMoney, 1000))

The code at this time, this is pointing to window?

Because of the callback, the runtime is already under Window

Const btn = document.getElementById ('btn') function payMoney () {console.log (' pay money'); console.log (this);} function debounce (func, delay) {let timer return function () {clearInterval (timer) timer = setTimeout (_ = > func (), delay)} btn.addEventListener ('click', debounce (payMoney, 1000))

Solution.

Save the this before setTimeout, and the this points to the button

Const btn = document.getElementById ('btn') function payMoney () {console.log (' pay money'); console.log (this) } function debounce (func, delay) {let timer / / this function is returned only when clicked, so this is the return function () {let context = this clearInterval (timer) timer = setTimeout (_ = > {func.apply (context)}, delay)} btn.addEventListener ('click', debounce (payMoney, 1000)) pointing to the button.

To consider the parameters, add arg

Const btn = document.getElementById ('btn') function payMoney () {console.log (' pay money'); console.log (this);} function debounce (func, delay) {let timer return function () {let context = this let args = arguments clearInterval (timer) timer = setTimeout (_ = > {func.apply (context) console.log (context, args);}, delay)} btn.addEventListener ('click', debounce (payMoney, 1000)) throttling

After triggering once, prevent triggering again and again.

Scrolling screen: statistics of the user's behavior of scrolling the screen to make a corresponding web page response

When users keep scrolling, requests will continue to be generated and will continue to increase accordingly, which can easily lead to ⛔️ network congestion.

We can execute the task as soon as the event is triggered, and then set a time interval limit during which the operation is ignored no matter how the user scrolls.

If the user's scrolling behavior is detected after the time is up, perform the task again. And set the time interval.

First, write a code that changes the background color of the page while changing the size of the page

Function coloring () {let r = Math.floor (Math.random () * 255g) let g = Math.floor (Math.random () * 255i) let b = Math.floor (Math.random () * 255i) document.body.style.background = `rgb (${r}, ${g}, ${b}) `} window.addEventListener ('resize', coloring) function throttle (func, delay) {let timer return function () {timer = setTimeout (_ = > {func ()}) Delay)}} window.addEventListener ('resize', throttle (coloring, 2000))

Determine whether the triggered event is within the time interval

Not present: trigger event

In: do not trigger events

Function throttle (func, delay) {let timer return function () {/ / timer is assigned and returns directly, that is, no task if (timer) {return} / / timer is not assigned at this time Or timer has finished executing / / deferring the execution of timer to timer = setTimeout (_ = > {func () / / after delaying execution we need to clear the value of timer timer = null}, delay)}} window.addEventListener ('resize', throttle (coloring, 2000))

Resolve this pointing (although the current example is under Window)

Function throttle (func, delay) {let timer return function () {let context = this let args = arguments / / timer is assigned and returns directly, that is, no task if (timer) {return} / / timer is not assigned at this time Or timer has finished executing / / deferring execution for timer assignment timer = setTimeout (_ = > {func.apply (context, args) / / after delaying execution we need to clear the value of timer timer = null}, delay}} window.addEventListener ('resize', throttle (coloring, 1000))

Throttling core: another common time interval between events is to use the Date object

Function throttle (func, delay) {/ / We need to compare with the previous point in time to determine whether the time interval has elapsed / / on the periphery of the return function to avoid being automatically modified every time let pre = 0 return function () {/ / save the time of execution of the function let now = new Date () / / has just started Be sure to execute if (now-pre > delay) {/ / after the time interval has elapsed, you can execute the function func () / / and reset the interval point pre = now} window.addEventListener ('resize', throttle (coloring, 1000))

Solve the parameter problem

Function throttle (func, delay) {let pre = 0 return function () {let context = this let args = arguments let now = new Date () if (now-pre > delay) {func.apply (context, args) pre = now}} window.addEventListener ('resize', throttle (coloring, 1000)) these are all the contents of the article "how to achieve Shake Prevention and throttling in JavaScript". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report