当前位置:网站首页>Anti shake and throttling
Anti shake and throttling
2022-06-26 00:22:00 【Senora】
Anti shake and throttling
- Shake proof : When javascript When the trigger frequency of the function in is particularly high , You need to limit how often it triggers .
- throttle : Means to trigger events continuously but in n Function is executed only once in seconds . Throttling dilutes the frequency of function execution .
One 、 difference
Like crazy ‘ Grab tickets ’ Button
- Shake proof ( Not immediately ): No matter how many times you go crazy , I will submit your last click only when you are not crazy .
- Shake proof ( Execute immediately ): No matter how many times you go crazy , I only submit your first .
- throttle : No matter how many times you go crazy , Only count you once in a certain period of time .
Two 、 Shake proof (debounce)
Refers to when an event triggers n Seconds before the callback , If in n Second triggered again , Then recalculate the time .( After triggering an event , Before the next trigger , If the intermediate interval exceeds the set time, the request will be sent , If it is triggered all the time, the request will not be sent )
characteristic : Wait for an operation to stop , Operate at intervals .
- Continuous trigger does not execute
- Do not trigger for a period of time before executing
Main application scenarios :
- scroll Event scrolling triggers
- Search box input query
- Form validation
- Button to submit Events
- Browser window zoom ,resize event
such as : Monitor browser scrolling Events , Returns the distance between the current roll bar and the top .
function showTop () {
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
console.log(' Scroll bar position :' + scrollTop);
}
window.onscroll = showTop // When scrolling, it will be executed very frequently
The anti shake function is divided into Not an immediate Executive and Executive now .
- Not an immediate Executive : The function does not execute immediately after the event is triggered , It's stopping triggering behavior n Seconds later , If in n Seconds to trigger the event , The function execution time is recalculated .
- Executive now : The function executes immediately after the event is triggered , then n Does not trigger the event in seconds to continue the function's effect .
// Not an immediate version
function debounce(fn, delay) {
let timeout; // Create a tag to store the return value of the timer
return function () {
clearTimeout(timeout); // Whenever an event is triggered, the previous setTimeout clear fall
timeout = setTimeout(() => {
// And then create a new one setTimeout, This will ensure that the characters are typed in this way interval If there are any characters to input in the interval , They don't execute fn function
fn.apply(this, arguments);
}, delay);
};
}
window.onscroll = debounce(showTop,1000)
// Execute version now
function debounce(fnc, delay) {
let timeout;
return function () {
clearTimeout(timeout); // Clear the last timer each time
if (!timeout) fnc.apply(this, arguments) // If timeout Did not reset to null Then execute the function
timeout = setTimeout(() => {
// At the end of the clock timeout Set as null
timeout = null;
}, delay)
}
}
window.onscroll = debounce(showTop, 1000)
Used in return function fn.apply(this, argument) Not directly fn(), It's to make debounce The function returned by the function this Direction is constant and still acceptable e Parameters .
3、 ... and 、 throttle
If an event continues to trigger , Is every n Once per second .
characteristic : After waiting for a certain interval , To operate .
- Continuous triggering does not execute multiple times
- At a certain time / Other intervals ( Such as sliding height ) To perform
Main application scenarios :
- DOM The drag function of elements is realized
- Shooting games
- Calculate the distance the mouse moves
- monitor scroll event
- Product search list 、 Commodity window, etc
function debounce(fnc, delay) {
let done = 1; // Record whether it is executable
return function () {
if(done) {
fnc.apply(this, arguments)
done = 0 // Set as non executable after execution
setTimeout(()=>{
// When the timing is over, it will be set to executable
done =1
}, delay)
}
}
}
window.onscroll = debounce(showTop, 1000)
Four 、
Another kind of view :
// throttle : Clear the timer inside the timer , Rhythmic execution events
function throttle(callback, delay = 1000){
let timer = null;
function f(){
if(!timer){
timer = setTimeout(() => {
callback && callback.call(this);
clearTimeout(timer);
timer = null;
}, delay);
}
}
return f;
}
// Shake proof : Clear the timer before the timer , Execute only the last event , It can extend the execution time indefinitely
function debounce(callback, delay = 1000) {
let timer = null;
function f() {
clearTimeout(timer);
timer = setTimeout(() => {
callback && callback.call(this);
}, delay);
}
return f;
}
边栏推荐
- 2021-04-28
- Smt贴片机保养与维护要点
- EasyConnect连接后显示未分配虚拟地址
- no_ Expand and use_ concat
- dbca静默安装及建库
- JS to input the start time and end time, output the number of seasons, and print the corresponding month and year
- My blog is 2 years old and 167 days old today. I received the pioneer blogger Badge_ Old bear passing by_ Sina blog
- Detailed explanation of redis
- 19c安装psu 19.12
- 【ROS进阶篇】第一讲 常用API介绍
猜你喜欢
![Mysql5.7 is in the configuration file my Ini[mysqld] cannot be started after adding skip grant tables](/img/b2/2b87b3cea1422e2a860f5e0e7dcc40.png)
Mysql5.7 is in the configuration file my Ini[mysqld] cannot be started after adding skip grant tables

鼠标拖拽围绕某个物体旋转展示

Redis memory elimination mechanism

When installing PSU /usr/bin/ld:warning: -z lazload ignore

What is micro service

My blog is 2 years old and 167 days old today. I received the pioneer blogger Badge_ Old bear passing by_ Sina blog

MySQL master-slave replication

渲云携手英特尔,共创云渲染“芯”时代

Core ideas of SQL optimization

"Seamless" deployment of paddlenlp model based on openvinotm development kit
随机推荐
EBS r12.2.0 to r12.2.6
SSL unresponsive in postman test
10.3.1、FineBI_ Installation of finebi
no_ Expand and use_ concat
[advanced ROS] Lecture 1 Introduction to common APIs
js数组中修改元素的方法
Ffmpeg version switching
Drag the mouse to rotate the display around an object
Function and principle of SPI solder paste inspection machine
机器视觉:照亮“智”造新“视”界
Display unassigned virtual address after easyconnect connection
What are AOI, X-ray and ICT in SMT industry? What does it do?
Use js to obtain the last quarter based on the current quarter
Circuit board edge removal - precautions for V-CUT splitting machine
tensorrt pb转uff问题
86. (cesium chapter) cesium overlay surface receiving shadow effect (gltf model)
Xiaohongshu microservice framework and governance and other cloud native business architecture evolution cases
10.2.3、Kylin_kylin的使用,维度必选
贴片机供料器(feeder)飞达的种类,如何工作
DBCA silent installation and database building