当前位置:网站首页>Simple introduction to thoroughly understand anti shake and throttling

Simple introduction to thoroughly understand anti shake and throttling

2022-06-22 03:26:00 Lao Zhu Yubing

        The topic of today's headline is to write an anti shake function ,, According to the words entered by the user , Submit the backend for fuzzy query , Display the results returned by the server in the order of input .
    
        Original title , What the interviewer wrote is to pay attention to anti shake and order .

      His request is :  For example, the input is submitted three times very quickly a, b,c Three letters . Due to the slow response of the server , The client has submitted c Inquire about , But the server only returns b Query results of ( This uses closures , In fact, there are problems with closures , Typical how to handle exceptions ).
      

        The question given by the interviewer is really representative , Problems often encountered in front-end development , repeat , Form resubmission , Both front and back-end development should understand . This question is about 2012 year 6 month , Tencent network www.qq.com The home page is revised and launched , Do a search module is very similar , At that time, Tencent was my first front-end development job in my career .

        At that time, this project , Filled a few holes :

         1. Must use native javascript Code , At that time, Tencent won't let you introduce jquery, Introduce a big js How much money is wasted by such a large number of visits ?:)
         2. It is the problem of layer covering , Enter key The keyword spring layer is spread under the input box , At that time, there were... Under the search box flash, If you are not careful, you will be flash Cover up
    The most pitiful thing is that there are advertisements flying around
         3. Secondly, the number of smart prompt elements returned by the backend is different , It is also possible not to return , The number of elements is different , You need a proxy mechanism , Bubbling to upper layer
         4. The other is css The problem of , Webpage / picture / The blue boxes of columns such as video are to be covered , Ladies and gentlemen, look carefully , Move the mouse to “ Webpage ” There is a blue border before the drop-down , It disappeared after moving . The first version also records where the user's mouse moved from , Click on that column , It is complicated to click and associate with keywords .

         5. Because as a module , Namely css Dynamic loading , Dynamic loading is simple , Loading in can be used , Don't conflict with others , It is also trivial to handle .

         6. Keyword search related to classification column , And logging

         7. exception handling

          The other is the two questions that the interviewer said . I think the most classic is anti shake . Simple though , But it's classic , Later on .

 

    When I was working on the project , I don't know if I am not good at learning , I don't know the concept of anti shake , that   Let's introduce anti shake . The following code tests , It will waste a lot of resources to execute the program , Here is only the output console.log(), It does not consume much resources , If the database batch query has a great impact . Run the following program , Open the browser , Scroll the scroll bar or zoom in and out the window , The browser console will output a bunch of log.

<html>
<head>
<meta charset="utf-8" />
<style>
  body {font-size:12px; height:2000px;}
</style>
</head>
<body>
 Access page , Open the browser console , Use the mouse to scroll or resize the browser to see the effect 
<script>
// rolling 
window.onscroll  = function(){
	console.log(' Scroll bar position :' + document.body.scrollTop || document.documentElement.scrollTop)
}
// Resize window 
window.onresize = () => {
      console.log(' Window width x high :' + window.innerWidth+'x'+window.innerHeight)
}
</script>
</body>
</html>

Function anti shake (debounce)

Anti shake function : A frequently triggered operation , Within the prescribed time , Let it only take effect for the last time , The previous does not take effect .
  Look at the anti shake function debounce(fn,delay),delay Parameter is 1 second ,1 Second calls the anti shake function no matter how many times , Only once .

          Anti shake is easy to understand from the literal meaning . A typical application is taking pictures , It is estimated that everyone is impressed , The photos taken by the camera without anti shake have a lot of ghosting . Anti shake is to make the camera shoot only once .

The above items need anti shake, that is, the mouse is in Classification area When moving , If a user from a web page --》 picture --》 Video moves to music , Just record the user's movement to music . There is also very fast keyword input, such as input the Philippines , You can actually query Philippine keywords . Instead of typing “ Fei ” Check once “ Filipino ” Check once “ the Philippines ” Check once .

Let's take the simplest example , The browser will find console The console outputs many times , But computing resources are limited , So we need to control the speed , This is like playing strange games , Don't wait for the full blood progress bar to complete , The game can't start .

Code up , Look at the anti shake function

/*  Function anti shake ,
@param fun   The name of the function to be anti shake 
@param delay  Anti shake interval 
*/
function debounce(fun, delay) {
    return  (args) => {
        clearTimeout(fun.id) // Clear timer 
        fun.id = setTimeout(()=> {
            fun.call(this, args)
        }, delay)
    }
}

After the above example, you must know , What is anti shake , And how to anti shake at the front end . As for the back-end, how to prevent shaking ? If you are interested, I can do the integral system in Tencent search , An article written , use memcache perhaps redis In fact, anti shake is realized

http://blog.sina.com.cn/s/blog_467eb8ca0100zmvb.html

What the hell is throttling ? 

Function throttling (throttle)

Function throttling
After a function is executed once , Only when the execution cycle is greater than the set execution cycle, the second execution will be performed .
Throttling function ,throttle(fun,delay) Parameter is 1 second , No matter how long it lasts , Once a second , And only execute once per second .

Let's make an analogy , Just a basin of water , Flow out slowly , Not bang It just fell down . This is very simple. You can see the code of function throttling in the example .

The one above  // Function throttling

// Function throttling 
function throttle(fun,delay){
    let valid = true
    return function(args) {
       if(!valid){
           // Rest time   No reception 
           return false
       }
       //  working hours , Execute the function and set the status bit to invalid during the interval 
        valid = false
        setTimeout(() => {
            fun.call(this, args)
            valid = true;
        }, delay)
    }
}

It is easy to implement function throttling on the server side , It is better to put it in asynchronous execution , use sleep Functions can be executed regularly .

On the functions of anti chattering and throttling , It's all written below , You can quickly input letters in the input box , Then open the browser console , Self testing .

<html>
<head>
<meta charset="utf-8" />
<style>
  body {font-size:12px;}
  span { width:60px; height:22px; display:inline-block;}
</style>
</head>
<body>
	<span class="tip"> No anti shake test </span> <input id="text" />
	<br>
	<span class="tip"> Anti shake test </span> <input id="input" />
	<br>
	<span class="tip"> Throttling test </span> <input id="throttle" /> <br />

</div>
<script>
// No anti shake request 
function ajax(content) {
  console.log('ajax request data ' + content)
}

let input = document.getElementById('text')

input.addEventListener('keyup', function (e) {
    ajax(e.target.value)
})

/*
*/

/*  Function anti shake ,
@param fun   The name of the function to be anti shake 
@param delay  Anti shake interval 
*/
function debounce(fun, delay) {
    return  (args) => {
        clearTimeout(fun.id) // Clear timer 
        fun.id = setTimeout(()=> {
            fun.call(this, args)
        }, delay)
    }
}

let inputb = document.getElementById('input')
let debounceAjax = debounce(ajax, 1000)  // function ajax Add anti shake , interval 1 second 
inputb.addEventListener('keyup', function (e) {
	debounceAjax(e.target.value)
})


// Function throttling 
function throttle(fun,delay){
    let valid = true
    return function(args) {
       if(!valid){
           // Rest time   No reception 
           return false
       }
       //  working hours , Execute the function and set the status bit to invalid during the interval 
        valid = false
        setTimeout(() => {
            fun.call(this, args)
            valid = true;
        }, delay)
    }
}
let throttleAjax = throttle(ajax, 1000)

let inputc = document.getElementById('throttle')
inputc.addEventListener('keyup', function(e) {
	throttleAjax(e.target.value)
})
</script>
</body>
</html>

summary

  • Function anti shake and function throttling are to prevent frequent triggering at a certain time .
  • Function anti shake is to execute only the last time in a certain period of time , Function throttling is executed at small intervals .

Combined with application scenarios

  • debounce Shake proof  
    • window Trigger resize once
    • The scrolling operation records the final status
    • Mouse click to trigger ,mousedown( Trigger only once per unit time )
    • Input parameter verification , Just check it once
  • throttle throttle
    • search Search Lenovo , When users are constantly entering values , Save requested resources
    • Listen for rolling events , For example, whether to slide to the bottom to automatically load more , use throttle To judge
    • monitor window Of resize many times
    • Calculate the mouse movement distance
    • canvas drawing
    • Shooting games , Unit time click button , Click the mouse to fire a bullet

 

原网站

版权声明
本文为[Lao Zhu Yubing]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220307007323.html