当前位置:网站首页>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
边栏推荐
- Real MySQL interview questions (25) -- common group comparison scenarios
- 雷达图canvas
- 制造业数字化转型存在问题及原因分析
- MDM data cleaning function development description
- Analysis on the problems and causes of digital transformation of manufacturing industry
- 三项最高级认证,两项创新技术、两大优秀案例,阿里云亮相云原生产业大会
- fastjson中的@JSONField注解
- Differences between fs4059a and fs5080e charging chips
- 数字藏品——新的投资机遇
- The performance of nonstandard sprintf code in different platforms
猜你喜欢

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

技术开发团队视角看到的数字藏品机遇与挑战

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

Wechat applet: Puzzle toolbox

Wechat applet: an artifact for calculating the full amount of orders

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

Behind the hot digital collections, a strong technical team is needed to support the northern technical team

What is the magic of digital collections? Which reliable teams are currently developing

runc 符号链接挂载与容器逃逸漏洞预警(CVE-2021-30465)

Redis cache penetration solution - bloom filter
随机推荐
线性表 链表结构的实现
The performance of nonstandard sprintf code in different platforms
Mobile phone wireless charging dual coil 15W scheme SOC IC ip6809
What does the English letter PC mean? What does the Internet PC mean
The difference between SaaS software and traditional software delivery mode
What is the magic of digital collections? Which reliable teams are currently developing
Wechat applet: future wife query generator
Pit filling for abandoned openssl-1.0.2 (.A to.So)
Yingjixin ip6806 wireless charging scheme 5W Qi certified peripheral simplified 14 devices
Explanation of penetration test process and methodology (Introduction to web security 04)
PAT 乙等 1025 反转链表
June 22, 2022: golang multiple choice question, what does the following golang code output? A:3; B:1; C:4; D: Compilation failed. package main import ( “fmt“ ) func mai
Real MySQL interview question (XXVIII) -- case - Analysis of indicators of communication operators
PAT 乙等 1019 C语言
runc 符号链接挂载与容器逃逸漏洞预警(CVE-2021-30465)
Oracle exception
visdom画多条动态损失曲线
Basic calculator for leetcode topic analysis
MySQL面试真题(二十五)——常见的分组比较场景
The construction of digital factory can be divided into three aspects