当前位置:网站首页>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
- 刷题---二叉树--2
- CV2 in OpenCV VideoWriter_ Fourcc() function and cv2 Combined use of videowriter() function
- Go learning notes - multithreading
- arcgis js 4. Add pictures to x map
- AI中台技术调研
- 排序---
- drools执行完某个规则后终止别的规则执行
- Take you ten days to easily finish the finale of go micro services (distributed transactions)
- 【C语言】杨辉三角,自定义三角的行数
猜你喜欢
BOM DOM
kubenetes中port、targetPort、nodePort、containerPort的区别与联系
From scratch, develop a web office suite (3): mouse events
Is the neural network (pinn) with embedded physical knowledge a pit?
ThreadLocal的简单理解
AI mid stage technology research
Natural language processing series (I) -- RNN Foundation
drools动态增加、修改、删除规则
drools中then部分的写法
(C语言)输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
随机推荐
AI mid stage technology research
High performance erasure code coding
String palindrome hash template question o (1) judge whether the string is palindrome
Jenkins用户权限管理
(C语言)输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
Simple use of drools decision table
Leetcode739 每日温度
Jenkins user rights management
drools动态增加、修改、删除规则
(C语言)3个小代码:1+2+3+···+100=?和判断一个年份是闰年还是平年?和计算圆的周长和面积?
The second composition template of postgraduate entrance examination English / chart composition, English chart composition is enough
AAAI 2022 | Peking University & Ali Dharma Institute: pruning and compression of pre training language model based on comparative learning
From scratch, develop a web office suite (3): mouse events
Go learning notes - go based interprocess communication
测试左移和右移
Docker compose configuration mysql, redis, mongodb
Discrimination of the interval of dichotomy question brushing record (Luogu question sheet)
Sse/avx instruction set and API of SIMD
CDA数据分析——Excel数据处理的常见知识点归纳
arcgis js 4. Add pictures to x map