JavaScript anti-shake and throttling detailed explanation

JavaScript anti-shake and throttling detailed explanation

Debounce

Definition: For events that are triggered continuously in a short period of time, such as scrolling events, anti-shake means that the event processing function is executed only once within a certain time limit.

Regarding anti-shake, take the example of pressing a spring with your finger. Press the spring with your finger and keep pressing. The spring will not bounce until you release your finger.

Example resize:

function debounce(fn, wait){
    var timer = null;
    return ()=>{
        if(timer !== null){
            clearTimeout(timer);
        }
        timer = setTimeout(fn, wait);
    }
}
function handle(){
    console.log(Math.random());
}
window.addEventListener("resize",debounce(handle, 1000));

The above is the non-immediate execution version

Immediate execution version

function debounce(fn, wait){
	let timeid, flag = true;
	return () => {
		clearTimeout(timeid);
		if(flag){
			fn();
			flag = false;
		}else{
			timeid = setTimeout(()=>{
				flag = true;
			}, wait);
		}
	}
}

Dragging the browser window triggers resize, but the handle function is not triggered at this time. The timer starts counting. If the resize is triggered again within the timing time, the timer will start again. The advantage of this is that dragging the browser window to trigger resize does not execute the handle function frequently, but only allows it to run when it is needed, effectively eliminating redundancy.

Common writing methods:

const debounce = (func, delay = 200) => {
  let timeout = null
  return function () {
    clearTimeout(timeout)
    timeout = setTimeout(() => {
      func.apply(this, arguments)
    }, delay)
  }
}

Throttle

Definition : Let the event execute only once within a certain period of time.

The original intention is to be like the dripping of water from a faucet, executing only once within a specified time, reducing frequent and repeated execution.

Such as search box input event.

Calculate by timestamp:

function throttle(fn,wait){
  let startTime = 0;
  return function(){
    let endTime = Date.now();
    if(endTime-startTime>wait){
      fn();
      startTime = endTime;
    }
  }
}

By timer:

function throttle(fn,wait){
  let timeid = null;
  return function(){
    if(!timeid){
       timeid = setTimeout(function(){
         fn();
         timeid = null;
       },wait)
    }
  }
}

Summarize

This article ends here. I hope it can be helpful to you. I also hope that you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Analysis of JavaScript's anti-shake throttling function
  • What is JavaScript anti-shake and throttling
  • A brief discussion on JavaScript throttling and anti-shake
  • JavaScript anti-shake and throttling explained
  • Do you know about JavaScript anti-shake and throttling?

<<:  Docker time zone issue and data migration issue

>>:  XHTML Tutorial: XHTML Basics for Beginners

Recommend

Html page supports dark mode implementation

Since 2019, both Android and IOS platforms have s...

JavaScript implements simple calculator function

This article shares the specific code of JavaScri...

JavaScript to implement a simple web calculator

background Since I was assigned to a new project ...

How to introduce pictures more elegantly in Vue pages

Table of contents Error demonstration By computed...

Detailed explanation of the use of React.cloneElement

Table of contents The role of cloneElement Usage ...

25 Examples of News-Style Website Design

bmi Voyager Pitchfork Ulster Grocer Chow True/Sla...

How to modify Flash SWF files in web pages

I think this is a problem that many people have en...

A brief discussion on Mysql specified order sorting query

Recently, I have been working on a large-screen d...

Detailed usage of docker-maven-plugin

Table of contents Docker-Maven-Plugin Maven plugi...

Example code for converting Mysql query result set into JSON data

Mysql converts query result set into JSON data Pr...

Detailed steps to modify MySQL stored procedures

Preface In actual development, business requireme...

Analysis of the use of the MySQL database show processlist command

In actual project development, if we have a lot o...

Solve the mobile terminal jump problem (CSS transition, target pseudo-class)

Preface Many friends who have just come into cont...

Detailed process of installing logstash in Docker

Edit docker-compose.yml and add the following con...