Home > Web Front-end > JS Tutorial > body text

JavaScript function throttling and function debounce knowledge points learning

青灯夜游
Release: 2018-10-08 15:40:20
forward
2005 people have browsed it

This article shares knowledge points related to JavaScript function throttling and function debounce. Friends in need can learn and refer to it.

Concept

Throttle (throttle) prevents a function from executing too frequently and reduces calls that execute too quickly. This is called Throttle

Debounce (debounce) Debounce is to execute continuous function calls for a certain period of time only once

throttle Application scenarios

  • Implementation of dragging function of DOM elements (mousemove)

  • Mousedown/keydown event of shooting game (only one bullet can be fired per unit time)

  • Calculate the distance of mouse movement (mousemove)

  • Canvas simulates the drawing board function (mousemove

  • Search Lenovo (keyup

  • Listen to scroll events to determine whether to automatically load more when reaching the bottom of the page: after adding debounce to scroll, only after the user stops scrolling will it be determined whether it has reached the bottom of the page; If it is throttle, it will be judged once every time as long as the page scrolls

debounce application scenario

Every time resize/scroll triggers statistical events

Verification of text input (after continuously inputting text, send an AJAX request for verification, just verify once)

Implementation of function debounce

We take the scroll event as an example to explore how to print a hello world string when the window is scrolled once. If it is not throttled or debounced:

window.onscroll = function () {
 console.log('hello world');
}
Copy after login

In this way, every time it scrolls, In fact, multiple hello world will be printed. The idea behind function debounce is that some code cannot be executed continuously without interruption. Create a timer to run the code after the specified time interval. When the second When this function is called, it clears the previous timer and sets another one. If the previous timer has already been executed, this operation has no meaning. However, if the previous timer has not been executed yet, it actually replaces it. is a new timer. The purpose is to execute the function only after the request to execute the function has stopped for a period of time.

"Height Three" gives the most concise and classic debounce code, as follows:

function debounce(method, context) {
 clearTimeout(method.tId);
 method.tId = setTimeout(function() {
 method.call(context);
 }, 1000);
}

function print() {
 console.log('hello world');
}

window.onscroll = function() {
 debounce(print);
};
Copy after login

Make some more changes

function debounce(delay, action) {
 var tId;
 return function () {
  var context = this;
  var arg = arguments;
  if (tId) clearTimeout(tId);
  tId = setTimeout(function () {
   action.apply(context, arg);
  }, delay);
 }
}

window.onscroll = debounce(1000, print);
Copy after login

Implementation of function throttling

Function throttling is to allow continuously executed functions to be executed intermittently within a fixed period of time. Probably There are two ways to implement it.

One uses the timestamp to determine whether the callback execution time has arrived, records the timestamp of the last execution, and then executes the callback each time the event is triggered, and determines the distance between the current timestamp in the callback Whether the time interval of the execution timestamp has *s, if so, execute, and update the timestamp of the last execution, and so on.

var throttle = function(delay, action) {
 var last = 0;
 return function() {
  var curr = new Date();
  if (curr - last > delay) {
   action.apply(this, arguments);
   last = curr;
  }
 }
}
Copy after login

The second method is to use a timer. For example, when the scroll event is first triggered, print a hello world, and then set a 1000ms timer. After that, each time the scroll event is triggered, a callback is triggered. If it has already If a timer exists, the callback does not execute the method until the timer starts, the handler is cleared, and then the timer is reset.

var throttle = function(delay, action) {
 var timeout;
 var later = function () {
  timeout = setTimeout(function(){
   clearTimeout(timeout);
   // 解除引用
   timeout = null;
  }, delay);
 };
 later();
 if (!timeout) {
  action.apply(this, arguments);
  later();
 }
}
Copy after login

Update method:

function throttlePro(delay, action) {
 var tId;
 return function () {
  var context = this;
  var arg = arguments;
  if (tId) return;
  tId = setTimeout(function () {
   action.apply(context, arg);
   clearTimeout(tId);
   // setTimeout 返回一个整数,clearTimeout 之后,tId还是那个整数,setInterval同样如此
   tId = null;
  }, delay);
 }
}
Copy after login

The above is the entire content of this chapter. For more related tutorials, please visit JavaScript Video Tutorial!

The above is the detailed content of JavaScript function throttling and function debounce knowledge points learning. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template