当前位置:网站首页>JS interview question - anti shake function
JS interview question - anti shake function
2022-06-23 05:50:00 【Zhangshao】
List of articles
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 .

<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 .

<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 .

<!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

<!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

<!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

<!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 .

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
边栏推荐
- What does the English letter PC mean? What does the Internet PC mean
- Wechat applet: production and generation of love guarantee
- JS面试题----防抖函数
- Yingjixin launched 4 series of lithium batteries 100W mobile power supply voltage rise and fall scheme SOC chip ip5389
- PAT 乙等 1020.月饼
- MySQL面试真题(二十六)——滴滴2020年笔试题
- Special research on Intelligent upgrading of heavy trucks in China in 2022
- What is the reason for the black screen of the computer monitor when the computer is turned on? What should I do about the black screen of the computer monitor
- jvm-06.垃圾回收器
- How does win11 enable mobile hotspot? How to enable mobile hotspot in win11
猜你喜欢

技能自检 | 想当测试Leader,这6项技能你会吗?

A bit of knowledge - folding forging and Damascus steel

Use of visdom

MySQL面试真题(二十九)——案例-找到爱看的电影

高等数学(第七版)同济大学 习题1-8 个人解答

Adnroid activity截屏 保存显示到相册 View显示图片 动画消失
![[Stanford Jiwang cs144 project] lab2: tcpreceiver](/img/70/ceeca89e144907226f29575def0e4d.png)
[Stanford Jiwang cs144 project] lab2: tcpreceiver

True MySQL interview question (XXII) -- condition screening and grouping screening after table connection

MySQL面试真题(二十七)——RFM分析法对用户进行分类

visdom的使用
随机推荐
Leetcode topic resolution divide two integers
The performance of nonstandard sprintf code in different platforms
True MySQL interview question (XXII) -- condition screening and grouping screening after table connection
Prometheus, incluxdb2.2 installation and flume_ Export download compile use
What is the magic of digital collections? Which reliable teams are currently developing
runc 符号链接挂载与容器逃逸漏洞预警(CVE-2021-30465)
【owt】owt-client-native-p2p-e2e-test vs2017构建 6:修改脚本自动生成vs工程
Real MySQL interview question (30) -- shell real estate order analysis
啊哈C语言 第7章 有了它你能做更多的事(第27-28讲)
Kotlin android简单Activity跳转、handler和thread简单配合使用
[graduation season u; advanced technology Er] farewell to the confused self in the past two years. Regroup, junior I'm coming
技术开发团队视角看到的数字藏品机遇与挑战
PAT 乙等 1014 C语言
PAT 乙等 1010 C语言
The author believes that the so-called industrial Internet is a process of deep integration of industry and the Internet
数字藏品市场才刚刚开始
node中操作mongoDB
How does win11 enable mobile hotspot? How to enable mobile hotspot in win11
HierarchyViewer工具找不到 HierarchyViewer位置
Advanced Mathematics (Seventh Edition) Tongji University exercises 1-9 personal solutions