在react 中引入js

Debouncing in Javascript is an exercise to enhance browser performance during any time-consuming computations. If such a method is invoked frequently then it may degrade our web app performance. Debouncing is a programming practice used to ensure that a time-consuming task does not fire so often. In other words, it limits rates at which functions get invoked.

使用Javascript进行反跳是一种在任何耗时的计算过程中提高浏览器性能的练习。 如果经常调用这种方法,则可能会降低我们的Web应用性能。 防弹跳是一种编程实践,用于确保耗时的任务不会经常触发。 换句话说,它限制了调用函数的速率。

Application

应用

  • Debouncing can be implemented where searching works like when the user will be typing in the search box and the search results will come from the server. There we can hit server API after the user stops typing(after a certain delay). Here if on every change there is frequent server API hit then it will degrade our server performance very much.
  • Another application of debouncing is in content-loading webpages like Facebook and Twitter where the user keeps on scrolling. In these scenarios, if the scroll event is fired too frequently, there might be a performance impact, as it contains lots of videos and images. Thus the scroll event must make use of debouncing.

Implementation

实作

Let’s go ahead and create a React Project.

让我们继续创建一个React项目。

Open the App.js file and replace the following code

打开App.js文件并替换以下代码

import React, { useState } from "react";


function App() {
  const [name, setName] = useState("");


  const debounce = (func, delay) => {
    let debounceTimer;
    return function () {
      const context = this;
      const args = arguments;
      clearTimeout(debounceTimer);
      debounceTimer = setTimeout(() => func.apply(context, args), delay);
    };
  };


  const update = debounce(function (e) {
    console.log(e.target.value)
    setName(e.target.value)
  }, 1000);


  return (
    <div className="App">
      <input type="text" onChange={(e)=>{ e.persist(); update(e); }} />
    </div>
  );
}


export default App;

Explanation

说明

  • debounce function which will do the actual work of delaying invoking function.去抖动功能,它将完成延迟调用功能的实际工作。
  • OnChange of the input field, we get event and pass it to the update function as an argument.
  • Update calls debounce function with passing 2 arguments (a function and seconds)
  • We do e.persist() in OnChange because when we will try to access an event inside callback, event’s reference will be nullified and we get undefined. If you try out the above code without e.persist(), then you will realize what particular error appears in the console.我们在OnChange中执行e.persist() ,因为当我们尝试访问回调中的事件时,事件的引用将被无效,并且我们将得到未定义。 如果您在没有e.persist()的情况下尝试上述代码,那么您将意识到控制台中会出现什么特定错误。

For more information on e.persist(), please visit

有关e.persist()的更多信息,请访问

https://reactjs.org/docs/events.html

https://reactjs.org/docs/events.html

  • The general idea for debouncing is: 反跳的一般思路是: 1. Start with 0 timeout 1.从0超时开始 2. If the debounced function is called again, reset the timer to the specified delay2.如果再次调用去抖功能,则将计时器重置为指定的延迟 3. In case of timeout, call the debounced function3.如果超时,请调用去抖动功能 Thus every call to a debounce function resets the timer and delays the call.因此,每次去抖功能的调用都会重置计时器并延迟呼叫。

Here in the above code, after every 1 sec of typing pause, callback function will get executed and will set the value to state, and in between 1 sec if the user types again the timer will be reset again to 0.

在上面的代码中,每暂停输入1秒钟,回调函数就会执行一次并将其值设置为state,如果用户再次键入,则在1秒钟之间,计时器将再次重置为0。

Few points are taken from GeeksForGeeks.

从GeeksForGeeks中获得很少的分数。

Check out GitHub repository for source code.

查看GitHub存储库以获取源代码。

(Sankhadip Samanta)

Full Stack Developer, Code Quotient | Tech Writer and Social Media Handler at BlogMarch

全栈开发人员,代码商| BlogMarch的技术作家和社交媒体处理程序

Find me on Linkedin 😃 and Github 😅

在Linkedin和Github上找到我

翻译自: https://medium.com/swlh/debouncing-in-react-js-83befe93a5ee

在react 中引入js