I heard that the front-end interview handwritten "throttling and anti-shake" don't you know?

I haven't published a new article for a long time. I heard that everyone loves to watch animation, so come here all night


Throttling and Stabilization

This is a common question in front-end interviews, and you may be asked to write it by hand on the spot. 节流and 防抖are used to control the calling frequency of certain functions. For example, resizewhen we are in a window, we may need to request more content from the server to fill the viewable area because the viewable area becomes larger. But in the process of increasing the visible area, resizethe event will be triggered multiple times...it is not necessary to request once every time it is triggered... then it needs to be 节流防抖controlled

picture

Why throttling.gif

function resize(e) {
    console.log("窗口大小改变了");
}
window.addEventListener('resize', resize);

throttle

When resizethe event is triggered, it is not allowed to be triggered again within the specified time. If you encounter handwriting during the interview, you may ask about several implementation methods

1. Timestamp version

picture

Throttle Timestamp Version.gif

function throttle(func, delay) {
    var last = 0;
    return function () {
        var now = Date.now();
        if (now >= delay + last) {
            func.apply(this, arguments);
            last = now;
        } else {
            console.log("距离上次调用的时间差不满足要求哦");
        }
    }
}

picture

Throttling Timestamp Edition Execution.gif

2. Timer version

function throttle(func, delay) {
    var timer = null;
    return function () {
        if (!timer) {
            func.apply(this, arguments);
            timer = setTimeout(() => {
                timer = null;
            }, delay);
        } else {
            console.log("上一个定时器尚未完成");
        }
    }
}

picture

Throttle timer version execution.gif

Regardless of the above-mentioned writing methods, throttling means that the function is called multiple times within a period of time, and only the first time is valid.

So 节流it's like a gatekeeper, it only lets one person in every once in a whilepicture

Anti-shake (debounce)

防抖The difference 节流is that when the function is called multiple times within a period of time, only the last call is valid.

function debounce(func, delay) {
    var timeout;
    return function() {
        clearTimeout(timeout);
        timeout = setTimeout(()=>{
            func.apply(this, arguments);
        }, delay);
    }
}

So 防抖it's like the undecided area in a PK game, the next undecided person will kick out the previous undecided personpicture


Have you learned it? Those who like and bookmark must pass every exam, get promoted and raise their salary, and reach the pinnacle of life

I heard that if you follow Dashuai Laoyuan on Xiaopozhan, you can see more animation video tutorials at the first time

Guess you like

Origin blog.csdn.net/ezshine/article/details/124312146