How to write javascript throttling and anti shake functions by hand in interview
- 2021-09-04 23:11:13
- OfStack
During the interview, we often ask others what they understand about throttling and anti-shake. Strictly, you may be required to write throttling and anti-shake functions. Here, we put aside the loadsh tool library to write throttling and anti-shake
1. Throttle function throttle
// Throttling scheme 1 , every delay Time execution of 1 Time, controlled by switch
function throttle(fn, delay, ctx) {
let isAvail = true
return function () {
let args = arguments // Execute the task when the switch is turned on
if (isAvail) {
fn.apply(ctx, args)
isAvail = false // delay After time, the task switch is turned on
setTimeout(function () { isAvail = true }, delay)
}
}
}
// Throttling scheme 2 By calculating the start and end times
function throttle(fn,delay){
// On record 1 Starting time of sub-function
var lastTime = 0
return function(){
// Record the time when the current function is triggered
var nowTime = new Date().getTime()
// When the current time is subtracted from 1 The second execution time is longer than this specified interval before it triggers this function
if(nowTime - lastTime > delay){
// Binding this Point
fn.call(this)
// Synchronization time
lastTime = nowTime
}
}
}
2. Anti-shake debounceTail
2.1) Execute only the first time
// Anti-shake And execute for the first time
// Principle of adoption: Part 1 Operation trigger, continuous operation, last 1 This operation turns on the task switch (instead of executing the task), and the task will be displayed in the following 1 Triggered during the second operation)
function debounceStart(fn, delay, ctx) {
let immediate = true
let movement = null
return function() {
let args = arguments
// Execute the task when the switch is turned on
if (immediate) {
fn.apply(ctx, args)
immediate = false
}
// Empty up 1 Secondary operation
clearTimeout(movement)
// Task switch on
movement = setTimeout(function() {
immediate = true
}, delay)
}
}
2.2) Execute only the last time
// Anti-shake Tail execution
// Adoption principle: When operating continuously, the last set setTimeout Be clear Drop
function debounceTail(fn, delay, ctx) {
let movement = null
return function() {
let args = arguments
// Empty up 1 Secondary operation
clearTimeout(movement)
// delay After time, the task executes
movement = setTimeout(function() {
fn.apply(ctx, args)
}, delay)
}
}