当前位置:网站首页>Anti shake throttle
Anti shake throttle
2022-07-02 12:28:00 【There is no water in the sea】
One 、 Shake proof
1、 Application scenarios : Search Lenovo - Apply anti shake
Two 、 throttle
3、 ... and 、UnderScore Library implementation Shake proof throttle
<!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>Document</title>
</head>
<body>
<input type="text" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.4/underscore-min.js"></script>
<script> const inputEL = document.querySelector("input"); let counter = 0; // Anti shake for this function . Is constantly delaying backwards , If the user continues to input // inputEL.oninput = function () {
// console.log(` Sent the second ${++counter} Network request `); // }; // 1、 Use underscore Anti-shake treatment const inputChange = function () {
console.log(` Sent the second ${
++counter} Network request `); }; // inputEL.oninput = _.debounce(inputChange, 500); // throttle : Trigger at a certain frequency // 2、 Use underscore Conduct throttling treatment inputEL.oninput = _.throttle(inputChange, 2000); </script>
</body>
</html>
Four 、 Realize it by yourself Shake proof
1、 edition 1:debounce Basic implementation
function debounce(fn, delay) {
// 1、 Define a timer , Save the last timer
let timer = null;
// 2、 Functions that actually execute
const _debounce = function (...args) {
// Cancel the last timer
if (timer) clearTimeout(timer);
// Delay the
timer = setTimeout(() => {
// External incoming function
// fn(); // This is how it works , Equivalent to independent function call . therefore this It points to window,event Yes undefined
fn.apply(this, args);
}, delay);
};
return _debounce;
}
index.html
<!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>Document</title>
</head>
<body>
<input type="text" />
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.4/underscore-min.js"></script> -->
<script src="./1.debounce Basic implementation .js"></script>
<script> const inputEL = document.querySelector("input"); let counter = 0; // Anti shake for this function . Is constantly delaying backwards , If the user continues to input // inputEL.oninput = function () {
// console.log(` Sent the second ${++counter} Network request `); // }; // 1、 Use underscore Anti-shake treatment const inputChange = function (event) {
// this: It's an element object , event. There is a problem with our implementation . console.log(` Sent the second ${
++counter} Network request `, this, event); }; // inputEL.oninput = _.debounce(inputChange, 500); inputEL.oninput = debounce(inputChange, 500); // throttle : Trigger at a certain frequency // 2、 Use underscore Conduct throttling treatment // inputEL.oninput = throttle(inputChange, 2000); </script>
</body>
</html>
2、 edition 2:debounce Execute now - ( Hope to implement it immediately for the first time )
function debounce(fn, delay, immediate = false) {
// 1、 Define a timer , Save the last timer
let timer = null;
let isInvoke = false;
// 2、 Functions that actually execute
const _debounce = function (...args) {
// Cancel the last timer
if (timer) clearTimeout(timer);
// Determine whether immediate execution is required
if (immediate && !isInvoke) {
fn.apply(this, args);
isInvoke = true;
} else {
// Delay the
timer = setTimeout(() => {
// External incoming function
// fn(); // This is how it works , Equivalent to independent function call . therefore this It points to window,event Yes undefined
fn.apply(this, args);
isInvoke = false;
}, delay);
}
};
return _debounce;
}
3、 edition 3:debounce Cancel the function
function debounce(fn, delay, immediate = false) {
// 1、 Define a timer , Save the last timer
let timer = null;
let isInvoke = false;
// 2、 Functions that actually execute
const _debounce = function (...args) {
// Cancel the last timer
if (timer) clearTimeout(timer);
// Determine whether immediate execution is required
if (immediate && !isInvoke) {
fn.apply(this, args);
isInvoke = true;
} else {
// Delay the
timer = setTimeout(() => {
// External incoming function
// fn(); // This is how it works , Equivalent to independent function call . therefore this It points to window,event Yes undefined
fn.apply(this, args);
isInvoke = false;
timer = null;
}, delay);
}
};
// Encapsulation cancellation function
_debounce.cancel = function () {
if (timer) clearTimeout(timer);
timer = null;
isInvoke = false;
};
return _debounce;
}
<!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>Document</title>
</head>
<body>
<input type="text" />
<button id="cancel"> Cancel </button>
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.4/underscore-min.js"></script> -->
<!-- <script src="./1.debounce Basic implementation .js"></script> -->
<!-- <script src="./2.debounce-immediate Execute now .js"></script> -->
<script src="./3.debounce- Cancel the function .js"></script>
<script> const inputEL = document.querySelector("input"); let counter = 0; // Anti shake for this function . Is constantly delaying backwards , If the user continues to input // inputEL.oninput = function () {
// console.log(` Sent the second ${++counter} Network request `); // }; // 1、 Use underscore Anti-shake treatment const inputChange = function (event) {
// this: It's an element object , event. There is a problem with our implementation . console.log(` Sent the second ${
++counter} Network request `, this, event); }; // inputEL.oninput = _.debounce(inputChange, 500); // inputEL.oninput = debounce(inputChange, 500, true); const debounceChange = debounce(inputChange, 500, true); inputEL.oninput = debounceChange; // throttle : Trigger at a certain frequency // 2、 Use underscore Conduct throttling treatment // inputEL.oninput = throttle(inputChange, 2000); // Cancel the function const cancelBtn = document.querySelector("#cancel"); cancelBtn.onclick = () => {
debounceChange.cancel(); }; </script>
</body>
</html>
4、 edition 4:debounce Function return value
function debounce(fn, delay, immediate = false, resultCallback) {
// 1、 Define a timer , Save the last timer
let timer = null;
let isInvoke = false;
// 2、 Functions that actually execute
const _debounce = function (...args) {
// Cancel the last timer
if (timer) clearTimeout(timer);
// Determine whether immediate execution is required
if (immediate && !isInvoke) {
const result = fn.apply(this, args);
if (resultCallback) resultCallback(result);
isInvoke = true;
} else {
// Delay the
timer = setTimeout(() => {
// External incoming function
// fn(); // This is how it works , Equivalent to independent function call . therefore this It points to window,event Yes undefined
const result = fn.apply(this, args);
if (resultCallback) resultCallback(result);
isInvoke = false;
timer = null;
}, delay);
}
};
// Encapsulation cancellation function
_debounce.cancel = function () {
if (timer) clearTimeout(timer);
timer = null;
isInvoke = false;
};
return _debounce;
}
<!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>Document</title>
</head>
<body>
<input type="text" />
<button id="cancel"> Cancel </button>
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.4/underscore-min.js"></script> -->
<!-- <script src="./1.debounce Basic implementation .js"></script> -->
<!-- <script src="./2.debounce-immediate Execute now .js"></script> -->
<!-- <script src="./3.debounce- Cancel the function .js"></script> -->
<script src="./4.debounce- Function return value .js"></script>
<script> const inputEL = document.querySelector("input"); let counter = 0; // Anti shake for this function . Is constantly delaying backwards , If the user continues to input // inputEL.oninput = function () {
// console.log(` Sent the second ${++counter} Network request `); // }; // 1、 Use underscore Anti-shake treatment const inputChange = function (event) {
// this: It's an element object , event. There is a problem with our implementation . console.log(` Sent the second ${
++counter} Network request `, this, event); // Take the return value return "aaa"; }; // inputEL.oninput = _.debounce(inputChange, 500); // inputEL.oninput = debounce(inputChange, 500, true); const debounceChange = debounce(inputChange, 500, false, (res) => {
console.log(" Get the return value of the real function ", res); }); inputEL.oninput = debounceChange; // throttle : Trigger at a certain frequency // 2、 Use underscore Conduct throttling treatment // inputEL.oninput = throttle(inputChange, 2000); // Cancel the function const cancelBtn = document.querySelector("#cancel"); cancelBtn.onclick = () => {
debounceChange.cancel(); }; </script>
</body>
</html>
5、 ... and 、 Realize it by yourself throttle
1、 edition 1: throttle Basic implementation
function throttle(fn, interval) {
let lastTime = 0;
const _throttle = function () {
// Throttle this function
// fn();
let nowTime = new Date().getTime();
const remainTime = interval - (nowTime - lastTime);
if (remainTime <= 0) {
fn();
lastTime = nowTime;
}
};
return _throttle;
}
<!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>Document</title>
</head>
<body>
<input type="text" />
<button id="cancel"> Cancel </button>
<script src="./5.throttle- Basic implementation .js"></script>
<script> const inputEL = document.querySelector("input"); let counter = 0; const inputChange = function (event) {
console.log(` Sent the second ${
++counter} Network request `, this, event); }; // throttle : Trigger at a certain frequency inputEL.oninput = throttle(inputChange, 2000); </script>
</body>
</html>
2、 edition 2: throttle - leading Realization
<!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>Document</title>
</head>
<body>
<input type="text" />
<button id="cancel"> Cancel </button>
<!-- <script src="./5.throttle- Basic implementation .js"></script> -->
<!-- <script src="./6.throttle-leading Function realization .js"></script> -->
<script src="./7.throttle-training Function realization .js"></script>
<script> const inputEL = document.querySelector("input"); let counter = 0; const inputChange = function (event) {
console.log(` Sent the second ${
++counter} Network request `, this, event); }; // throttle : Trigger at a certain frequency , The third parameter , Decide whether to trigger the function for the first time inputEL.oninput = throttle(inputChange, 3000, {
leading: true, training: true, }); </script>
</body>
</html>
function throttle(
fn, interval, options = {
leading: true, training: false, }
) {
const {
leading, training } = options;
// 1、 Record the last time
let lastTime = 0;
// 2、 Event triggered , Functions that actually execute
const _throttle = function () {
// Throttle this function
// fn();
// 2.1、 Get the time when the current event is triggered
const nowTime = new Date().getTime();
if (!lastTime && !leading) lastTime = nowTime;
// The above writing is equivalent to the following writing
// if(lastTime == 0 && leading == false) lastTime = nowTime;
// 2.2、 Use the current trigger time, the previous time interval and the last start time , Calculate the trigger event function with multiple times remaining
const remainTime = interval - (nowTime - lastTime);
if (remainTime <= 0) {
// 2.3、 Real trigger function
fn();
// 2.4、 Keep the last trigger time
lastTime = nowTime;
}
};
return _throttle;
}
3、 edition 3: throttle - training Realization
function throttle(
fn, interval, options = {
leading: true, training: false, }
) {
const {
leading, training } = options;
// 1、 Record the last time
let lastTime = 0;
let timer = null;
// 2、 Event triggered , Functions that actually execute
const _throttle = function () {
// Throttle this function
// fn();
// 2.1、 Get the time when the current event is triggered
const nowTime = new Date().getTime();
if (!lastTime && !leading) lastTime = nowTime;
// The above writing is equivalent to the following writing
// if(lastTime == 0 && leading == false) lastTime = nowTime;
// 2.2、 Use the current trigger time, the previous time interval and the last start time , Calculate the trigger event function with multiple times remaining
const remainTime = interval - (nowTime - lastTime);
if (remainTime <= 0) {
if (timer) {
clearTimeout(timer);
timer = null;
}
// 2.3、 Real trigger function
fn();
// 2.4、 Keep the last trigger time
lastTime = nowTime;
return;
}
if (training && !timer) {
timer = setTimeout(() => {
timer = null;
lastTime = !leading ? 0 : new Date().getTime();
fn();
}, remainTime);
}
};
return _throttle;
}
<!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>Document</title>
</head>
<body>
<input type="text" />
<button id="cancel"> Cancel </button>
<!-- <script src="./5.throttle- Basic implementation .js"></script> -->
<!-- <script src="./6.throttle-leading Function realization .js"></script> -->
<script src="./7.throttle-training Function realization .js"></script>
<script> const inputEL = document.querySelector("input"); let counter = 0; const inputChange = function (event) {
console.log(` Sent the second ${
++counter} Network request `, this, event); }; // throttle : Trigger at a certain frequency , The third parameter , Decide whether to trigger the function for the first time inputEL.oninput = throttle(inputChange, 3000, {
leading: true, training: true, }); </script>
</body>
</html>
4、 edition 4: throttle - this, Cancel implementation
function throttle(
fn, interval, options = {
leading: true, training: false, }
) {
const {
leading, training } = options;
// 1、 Record the last time
let lastTime = 0;
let timer = null;
// 2、 Event triggered , Functions that actually execute
const _throttle = function (...args) {
// Throttle this function
// fn();
// 2.1、 Get the time when the current event is triggered
const nowTime = new Date().getTime();
if (!lastTime && !leading) lastTime = nowTime;
// The above writing is equivalent to the following writing
// if(lastTime == 0 && leading == false) lastTime = nowTime;
// 2.2、 Use the current trigger time, the previous time interval and the last start time , Calculate the trigger event function with multiple times remaining
const remainTime = interval - (nowTime - lastTime);
if (remainTime <= 0) {
if (timer) {
clearTimeout(timer);
timer = null;
}
// 2.3、 Real trigger function
fn.apply(this, args);
// 2.4、 Keep the last trigger time
lastTime = nowTime;
return;
}
if (training && !timer) {
timer = setTimeout(() => {
timer = null;
lastTime = !leading ? 0 : new Date().getTime();
fn.apply(this, args);
}, remainTime);
}
};
_throttle.cancel = function () {
if (timer) {
clearTimeout(timer);
timer = null;
lastTime = 0;
}
};
return _throttle;
}
<!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>Document</title>
</head>
<body>
<input type="text" />
<button id="cancel"> Cancel </button>
<!-- <script src="./5.throttle- Basic implementation .js"></script> -->
<!-- <script src="./6.throttle-leading Function realization .js"></script> -->
<script src="./8.throttle-this Function realization .js"></script>
<script> const inputEL = document.querySelector("input"); let counter = 0; const inputChange = function (event) {
console.log(` Sent the second ${
++counter} Network request `, this, event); }; // throttle : Trigger at a certain frequency , The third parameter , Decide whether to trigger the function for the first time const _throttle = throttle(inputChange, 3000, {
leading: true, training: true, }); inputEL.oninput = _throttle; // Cancel the function const cancelBtn = document.querySelector("#cancel"); cancel.onclick = () => {
_throttle.cancel(); }; </script>
</body>
</html>
边栏推荐
- The second composition template of postgraduate entrance examination English / chart composition, English chart composition is enough
- Addition, deletion, modification and query of MySQL table (Advanced)
- 高性能纠删码编码
- Leetcode - Sword finger offer 51 Reverse pairs in an array
- 防抖 节流
- The blink code based on Arduino and esp8266 runs successfully (including error analysis)
- (C language) octal conversion decimal
- 堆(优先级队列)
- Input a three digit number and output its single digit, ten digit and hundred digit.
- Leetcode922 按奇偶排序数组 II
猜你喜欢
甜心教主:王心凌
Sort---
Map和Set
刷题---二叉树--2
Less than three months after the programmer was hired, the boss wanted to launch the app within one month. If he was dissatisfied, he was dismissed immediately
In development, why do you find someone who is paid more than you but doesn't write any code?
mysql索引和事务
BOM DOM
mysql数据库基础
The blink code based on Arduino and esp8266 runs successfully (including error analysis)
随机推荐
【工控老马】西门子PLC Siemens PLC TCP协议详解
jenkins 凭证管理
Maximum profit of jz63 shares
Map和Set
Fresh, 2022 advanced Android interview must know 100 questions (interview questions + answer analysis)
Lekao: 22 year first-class fire engineer "technical practice" knowledge points
kubeadm join时出现错误:[ERROR Port-10250]: Port 10250 is in use [ERROR FileAvailable--etc-kubernetes-pki
Experiment of connecting mobile phone hotspot based on Arduino and esp8266 (successful)
测试左移和右移
The second composition template of postgraduate entrance examination English / chart composition, English chart composition is enough
Simple use of drools decision table
Drools terminates the execution of other rules after executing one rule
单指令多数据SIMD的SSE/AVX指令集和API
arcgis js 4. Add pictures to x map
Deep understanding of P-R curve, ROC and AUC
drools执行指定的规则
Drools executes the specified rule
Adding database driver to sqoop of cdh6
[C language] convert decimal numbers to binary numbers
Simple understanding of ThreadLocal