当前位置:网站首页>JS interview question: handwriting throttle function
JS interview question: handwriting throttle function
2022-07-25 11:55:00 【Front end watermelon brother】
Hello everyone , I'm brother watermelon , Today, let's write by hand (throttle) Throttling function .
before this , Let's briefly understand what the throttling function is .
What is the throttling function ?
Throttling function , Is to reduce the execution frequency of a function . Every once in a while , Only execute the function once .
Suppose we 1s To perform the 8 Secondary function :
1 2 3 4 5 6 78
---------------------
After adding throttling capacity , We let the function execute only at a specific time interval , And some of the functions are not really called :
// After throttling
1 3 5 6 8
---------------------
Common usage scenarios of throttling function
The scenario of using throttling is usually some events that will be triggered with high frequency , Including scrolling 、 Change the window size 、 Input content 、 Cursor movement events .
Their trigger frequency is very high , It is easy to cause some performance problems without restrictions .
Here are some common scenarios using throttling functions :
The search box is based on the content entered by the user , Prompt for intelligent completion . You need to reduce the pressure on the server by throttling
Scroll load at the bottom of the page . If throttling is not used , When the user scrolls to the bottom and sends the first request , Data has not been returned , Will continue to trigger the event rolling to the bottom , Cause a large number of requests to be sent at the same time . We can consider adding throttling , Remember to increase this time interval , Dealing with weak network environment .
adopt JS Listening window size changes resize event , Change the width of an element , You can reduce the redrawing operation of the browser by throttling .
Realization
We need to implement one throttle function , This function accepts the original function fn And time intervals wait, Then return a new function that supports throttling .
Usage is as follows :
const printNum = (num) => {
console.log(num);
}
// Set up
const throttled = throttle(printNum, 300);
throttled(0);
setTimeout(() => { throttled(1); }, 100);
setTimeout(() => { throttled(2); }, 200);
setTimeout(() => { throttled(3); }, 250);
// 0
// 3 (300ms+ Left and right rear output )
Implementation , As long as high-frequency functions are called continuously , Become a uniform and low-frequency call , Even the throttling function .
The core of the implementation is Use timestamp to control the call time of timer .
Let's first look at the code implementation :
function throttle(fn, wait = 0) {
let timerId;
let lastInvoke = Number.MIN_SAFE_INTEGER; // Last call time
return function(...args) {
// current time
const currTime = new Date().getTime();
// Time remaining until next execution
const remain = Math.max(lastInvoke + wait - currTime, 0);
// Update timer , Make sure that only one timer is running at the same time
clearTimeout(timerId);
timerId = setTimeout(() => {
lastInvoke = new Date().getTime();
fn(...args);
}, remain);
}
}
// Usage mode
const throttled = throttle(printNum, 300);
throttle(0);
demonstration demo:
https://codepen.io/F-star/pen/GRxvRRd?editors=0010
First, we need to save some private variables through closures :
The timestamp of the last time the original function was called lastInvoke;
Timer id, When a function is called , Clear the original timer , Execute a new timer , Make sure that only one timer is running at any time ;
The original function to be called fn;
Call interval wait
When calling throttle Enhanced function returned ,
First calculate the remaining time to call the next function remain: First, through lastInvoke + wait Calculate the timestamp that should be executed next time , Then subtract the current timestamp from this timestamp currTime, You can get the remaining time .
The remaining time may be negative , Let's say we call throttled The scenario executed again after a long time . In this case, we set it to 0, Then send the remaining time to setTimeout Internal execution .
When the timer is running , Before we execute the original function , To update lastInvoke. If you put it in the back , There may be errors due to the execution of the original function , Lead to lastInvoke Update failed .
The implementation of the above code is actually rough , Somewhat case Can't handle it .
If you want to implement a perfect throttling function , You can refer to lodash.throttle The implementation of the , It considers more boundary cases , And provides some additional functions , The code implementation is also more complex .
lodash.throttle Consider the following details :
On first execution , Execute in synchronous mode ;
It supports canceling execution in the middle (cancel);
Support immediate execution halfway (flush);
Returns the return value of the previous execution of the original function ;
You can choose whether to execute a round leading and trailing Boundary situation ;
…
ending
Implement a simple throttling function , The key is to maintain the timestamp of the last call to the original function , It is used to calculate the next execution time , And use a timer to execute .
The implementation of a relatively perfect throttling function is not simple , Some boundary conditions need to be considered , I recommend you to use famous lodash The tool library provides throttle Method .
I'm brother watermelon , Welcome to follow me , Learn more front-end interview questions .
边栏推荐
- JS中的函数
- 微信公众号开发 入手
- Linked list related (design linked list and ring linked list)
- Small program of vegetable distribution in community
- OneNET平台控制W5500开发板LED灯
- 【USB设备设计】--复合设备,双HID高速(64Byte 和 1024Byte)
- [imx6ull notes] - a preliminary exploration of the underlying driver of the kernel
- dirReader.readEntries 兼容性问题 。异常错误DOMException
- Brpc source code analysis (VII) -- worker bthread scheduling based on parkinglot
- Learn NLP with Transformer (Chapter 1)
猜你喜欢

Review in the middle of 2022 | understand the latest progress of pre training model

Maskgae: masked graph modeling meets graph autoencoders

【mysql学习09】
![There is no sound output problem in the headphone jack on the front panel of MSI motherboard [solved]](/img/e8/d663d0a3c26fce8940f91c6db4afdb.png)
There is no sound output problem in the headphone jack on the front panel of MSI motherboard [solved]

软件测试阶段的风险

MySQL historical data supplement new data

Similarity matrix, diagonalization condition

brpc源码解析(七)—— worker基于ParkingLot的bthread调度

JaveScript循环

Experimental reproduction of image classification (reasoning only) based on caffe resnet-50 network
随机推荐
Classification parameter stack of JS common built-in object data types
基于Caffe ResNet-50网络实现图片分类(仅推理)的实验复现
Small program of vegetable distribution in community
brpc源码解析(四)—— Bthread机制
Oracle parsing XML with the same name
Introduction to shortcut keys in debug chapter
【leetcode刷题】
JaveScript循环
各种控件==PYQT5
Various controls ==pyqt5
【高并发】SimpleDateFormat类到底为啥不是线程安全的?(附六种解决方案,建议收藏)
[electronic device notes 5] diode parameters and selection
程序员送给女孩子的精美礼物,H5立方体,唯美,精致,高清
Dynamic planning problem 03_ Maximum sub segment sum
Summary of combination problems of Li Kou brush questions (backtracking)
【mysql学习09】
JS数据类型以及相互转换
Similarity matrix, diagonalization condition
数据库完整性——六大约束学习
brpc源码解析(五)—— 基础类resource pool详解