preface

This is the third day of my participation in the Gwen Challenge

Function stabilization and throttling are a means of optimizing js code for high frequency execution. As front-end development is a must know, and of course, one of the interview questions,

Image stabilization function

How it works: Execute the callback function n seconds after the event is triggered. If the event is retriggered within n seconds, the timer is reset. The result is to consolidate frequently triggered events into one and execute them last

case

Requirement: The result of the input box is to print the result without input within the specified time when our keyboard is up

let input = document.getElementById('input')
function debounce(delay){
   let timer;
   return function(value,callback){
    clearTimeout(timer)
    timer = setTimeout(function(){
        callback(value)
    },delay)
   }
}
// To facilitate encapsulation, pass debugging printed results as callback
function fn(value){
    console.log(value)
}
var debounceFn = debounce(1000)
input.addEventListener('keyup'.function(e){ 
    debounceFn(e.target.value,fn)
})
Copy the code

Actual Application Scenarios

  • When using Echart and changing the browser width, you can use this function to re-render echart images to improve performance. (Although echarts has its own resize function)

  • The typical case is fuzzy search: n seconds after the input, the search request, n seconds after the input of the content, reset the timer. Fix search bugs by getting the last input before requesting it

Throttling function

Make sure you only call a handler once for a certain amount of time when an event is continuously raised.

Actual application form submission

A typical example is the repeated mouse click trigger, which stipulates that only one click of multiple clicks will work in n seconds

// If you don't use closures, it will be executed a few times after you click on them
// That's not what we want, what we want is, for example, the time is one second, even if you are faster, in one second, even if you click 1000 times, I will only do it once
// With closures, variables are stored in memory
function throttle(func,wait){
    let timeOut 
    return function(){
        if(! timeOut){ timeOut =setTimeout(function(){
                func()
                // After processing, no processing
                timeOut = null
            },1000)}}}function handle(){
    console.log(Math.random())
}
document.getElementById('thro').onclick = throttle(handle,1000)
Copy the code

A case of a combination of the two

Lazy loading of images is one of the most common ways to optimize performance in our front-end development. The following is an example of using anti-shake throttling.

HTML part
<img src="" data-src="Https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3205580013, & FM = 26 & gp = 0. 1833705086 JPG" alt="" />
   
Copy the code
Javascript part
var num = document.getElementsByTagName('img').length
    var img = document.getElementsByTagName('img')
    var n = 0 // Store the location where the image is loaded to avoid traversing from the first image every time
    var isLoadImg = false // Whether the images in the current container/page have been loaded
    var _clientHeight = document.documentElement.clientHeight // View area height
    var _scrollTop = document.documentElement.scrollTop || document.body.scrollTop // Height of scroll bar from top
    // Listen for window changes and recalculate the viewable area
    function computedClientHeight(){
        _clientHeight = document.documentElement.clientHeight // View area height
    }
    // When the page is loaded, the image of the viewable area is loaded
    lazyLoad()
    function lazyLoad(){
        // Get the height of the scrollbar from the top
        isLoadImg = n >= num
        _scrollTop = document.documentElement.scrollTop || document.body.scrollTop
        for(vari=n; i < num; i++){if(img[i].offsetTop <_clientHeight +_scrollTop) {
                if (img[i].getAttribute('src') = =' '){
                    img[i].src = img[i].getAttribute('data-src')
                }
                n + 1}}}/** * Simple throttling function throttle *@params {*}* func function to be executed * delay delay * time Must be executed once within the time period * flag Whether to continue to trigger the throttling function
    function throttle(func,wait,flag){
        let timeOut
        return function(){
            if (flag){
                return
            }
            if(! timeOut) { timeOut =setTimeout(function(){
                    timeOut = null
                    func()
                },wait)
            }
        }
    }
/** * Simple throttling function throttle *@params {*}* func function to be executed * delay delay * time Must be executed once within the time period * flag Whether to continue to trigger the throttling function 
function debounce(callback,delay) {
    let timer
    return function(arg) {
        clearTimeout(timer)
        timer = setTimeout(function(){
            callback(arg)
        },delay)
    }
}
// Use the throttling function - to achieve good performance lazy loading
window.addEventListener('scroll',throttle(lazyLoad,100,isLoadImg))
// Optimize the constantly triggered window changes using the anti-shake function
window.addEventListener('resize',debounce(computedClientHeight,800))
Copy the code