当前位置:网站首页>JS interview question - anti shake function

JS interview question - anti shake function

2022-06-23 05:50:00 Zhangshao

The first 1 topic : Anti shake function

  • principle : When an event is triggered continuously , stay n Seconds , The event did not trigger again , Only then will the callback be executed ; If n Seconds , It triggered the event again , Just re time

  • Applicable scenario :

    • search Remote search box : Prevent users from constantly entering , Constantly requesting resources ,n I only send 1 Time , Use anti shake to save resources
    • Button submit scenario , For example, like , Form submission, etc , Prevent multiple submissions
    • Listen for browser zoom events
    • Listen for browser scrolling Events
  • To assist in understanding : When you take the elevator , When someone keeps getting into the elevator ( Continuous trigger ), The elevator door won't close , No one enters within a certain time interval ( Stop continuous triggering ) Will be closed .

2022-06-22 22.38.56

<body>
    <!--  Input box  -->
     No anti shake input box <input>
    <script> // Get input box  const inputEl = document.querySelector('input') // Trigger function  let count = 0 const inputChange = function(){
       console.log(` The first ${
        ++count} Secondary call inputChange Method `) } // Input triggers  inputEl.oninput = inputChange </script>
</body>

Self defined anti shake function

The principle of realizing the anti shake function is , Pass in the function to execute , And the time to wait , After a series of treatments , Then execute the incoming function .

First step : Foundation anti shake

Definition setTimeout Delay the execution of the function ,clearTimeout Used to enter the next character before it has exceeded 1 Seconds to clear the timer , Create a new timer , If not cleared , So every character is separated 1s Calling method .

2022-06-22 22.55.26

<body>

    <!--  Definition setTimeout Delay the execution of the function ,clearTimeout Used to enter the next character before it has exceeded 1 Seconds to clear the timer , Create a new timer ,  If not cleared , So every character is separated 1s Calling method . -->
     Basic version anti shake <input>
    <script> const inputEl = document.querySelector('input') let count = 0 const inputChange = function(){
       console.log(` The first ${
        ++count} Secondary call inputChange Method `) } // Basic anti shake function  const debounce = function (fn, delay) {
       // Timer variable  let timer = null; const _debounce = function () {
       // The timer is not null Clear timer  if (timer) clearTimeout(timer); // The timer is empty. Recreate the timer  timer = setTimeout(()=>{
       // Execute callback function  fn() }, delay); }; return _debounce; }; inputEl.oninput = debounce(inputChange, 1000); </script>
</body>

Second, No : expand this And parameters

When defining the function in the previous step ,this Objects and event Parameters are missing , We need to get them back here , It only needs to be executed fn Function time , adopt call/apply/bind To change this Implementation , And pass in parameters .

2022-06-22 23.39.49

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> Expand this And parameters </title>
</head>
<body>
     Expand this And parameters <input>
    <script> const inputEl = document.querySelector('input') let count = 0 // add to  const inputChange = function(e){
       console.log(` The first ${
        ++count} Secondary call , The input is ${
        e.target.value}`) } const debounce = function (fn, delay) {
       let timer = null; const _debounce = function (...args) {
       if (timer) clearTimeout(timer); timer = setTimeout(()=>{
       // adopt call/apply/bind  Appoint this, And the incoming event object  fn.apply(this,args) }, delay); }; return _debounce; }; inputEl.oninput = debounce(inputChange, 1000); </script>
</body>
</html>

The third step : The function is executed immediately

In the anti shake function defined above , There is no immediate implementation , That is, when you enter the first character "j" When , Will not call the function , There may be some scenarios , Waiting for user input to complete before calling seems to be a slow response , You need to make a call when the first character is entered .
Here you can add a parameter to the incoming function , Indicates whether immediate execution is required , By default, you don't need , by false, Function is using a variable to save whether it needs to be executed for the first time , When the first execution is completed , Set this variable to false

2022-06-22 23.49.08

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> The function is executed immediately </title>
</head>
<body>
     The function is executed immediately <input>
    <script> const inputEl = document.querySelector('input') let count = 0 const inputChange = function(e){
       console.log(` The first ${
        ++count} Secondary call , The input is ${
        e.target.value}`) } const debounce = function (fn, delay, isImmediate = false) {
       let timer = null; // Execute the configuration variables immediately , The default is false: Not immediately  let isExcute = isImmediate; const _debounce = function (...args) {
       // Judge to execute immediately  if (isExcute) {
       // Close immediately after one execution  fn.apply(this, args); isExcute = false; } if (timer) clearTimeout(timer); timer = setTimeout(()=>{
       // adopt call/apply/bind  Appoint this, And the incoming event object  fn.apply(this,args) isExcute = isImmediate; }, delay); }; return _debounce; }; // Configure immediate execution  inputEl.oninput = debounce(inputChange, 1000, true); </script>
</body>
</html>

Step four : Cancel

Take a closer look. , Our anti shake function cannot be cancelled , As long as the time comes, it will be implemented , Just in case when the user has finished typing the content , Hasn't arrived yet 1 Second , But he has closed the window , Considering this situation , We have to arrange the cancellation function !
A function is also an object , We can bind another function to the function object , stay return Of _debounce Bind a cancel Method , Execute when cancellation is required cancel Method

2022-06-23 00.04.43

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> The function is executed immediately </title>
</head>
<body>
     The function is executed immediately <input> <br>
    <button> Cancel </button>
   
    <script> const inputEl = document.querySelector('input') const cancelBtn = document.querySelector("button"); let count = 0 const inputChange = function(e){
       console.log(` The first ${
        ++count} Secondary call , The input is ${
        e.target.value}`) } const debounce = function (fn, delay, isImmediate = false) {
       let timer = null; let isExcute = isImmediate; const _debounce = function (...args) {
       if (isExcute) {
       fn.apply(this, args); isExcute = false; } if (timer) clearTimeout(timer); timer = setTimeout(()=>{
       fn.apply(this,args) isExcute = isImmediate; }, delay); }; // The nature of closures is used here  _debounce.cancel = function () {
       if (timer) clearTimeout(timer); }; return _debounce; }; debounceFn = debounce(inputChange, 1000, true); // Cancel the call  inputEl.oninput = debounceFn; cancelBtn.onclick = debounceFn.cancel; </script>
</body>
</html>

Step five : Function return value

As defined above " Shake proof " Function has no return value , After the execution is completed , Hope to get the result of implementation , There are also two ways to get
Callback function
Add the fourth parameter to the input parameter of the anti shake function , It's a function , Used to obtain the result of the completion of the anti shake function

2022-06-23 00.19.05

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> Function return value </title>
</head>

<body>
     Function return value <input>
    <script> const inputEl = document.querySelector('input') let count = 0 const inputChange = function (e) {
       console.log(` The first ${
        ++count} Secondary call , The input is ${
        e.target.value}`); return ' Execution results '; } const debounce = function (fn, delay, isImmediate = false, callbackFn) {
       let timer = null; let isExcute = isImmediate; const _debounce = function (...args) {
       if (isExcute) {
       const result = fn.apply(this, args); callbackFn(result) isExcute = false; } if (timer) clearTimeout(timer); timer = setTimeout(() => {
       // Call the callback to pass in the result  const result = fn.apply(this, args) callbackFn(result) isExcute = isImmediate; }, delay); }; return _debounce; }; // Callback receive result const debounceFn = debounce(inputChange, 1000, true, function (result) {
       console.log(' Get the results of execution ', result) }); inputEl.oninput = debounceFn; </script>
</body>

</html>

promise

In the return function of the anti shake function , adopt promise To return a successful or failed result , The following code only determines the successful execution condition , Failure handling can also be added .
adopt promise The asynchronous function of the package needs to be called to get the response result , So put the anti shake function in the new function , Use the new function as oninput Function of event response .

2022-06-23 00.28.32

Use anti shake function in development to optimize the performance of the project , You can customize as above , You can also use third-party libraries .

lodash

https://www.lodashjs.com/docs/lodash.debounce#_debouncefunc-wait0-options

原网站

版权声明
本文为[Zhangshao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230417570433.html