This series also does not have any tricks, is to complete the usual interview some handwriting functions, test these simple implementation of the advantage is that you can see the basic coding level, and take a short time, a more comprehensive view of your code strength. Generally, there are not many boundary conditions, so that the interview time is not enough, the investigation is not comprehensive.

If you don’t know or are not clear about the API, just ask the interviewer directly, how to use the API under Google anyone can immediately understand the knowledge also can’t see the level. The key is in the implementation process, and your coding status, habits, clarity of thought and so on.

Note that it is a simple implementation, not a complete implementation. It is important to have clear concepts and clear implementation ideas. It is recommended to write pseudo-code first, and then implement specific functions.

The core concept of anti-shake throttling is that I have gone into a lot of detail in this article and I don’t want to go over it. Please read this article carefully for more details.

4. Function debounce

What is the

Basically, it’s a combination of multiple executions into one execution.

For example, if we set a time interval of 5 seconds, the (callback) function will be executed only when the event is fired after 5 seconds. If the event is fired within 5 seconds, the function will be refreshed for 5 seconds at least before the event is fired.

Simple handwriting implementation

implementation

  1. Step 0: Write a test case first, sometimes you can ask the interviewer to give a test case, to ensure the accuracy of understanding, if he does not give you, you must also make sure that you meet the requirements after writing a test case, do not implement the original communication is not in place, this also shows your communication skills.
// The function that the user executes frequently (the function that needs to be defended) may be an asynchronous request list, which is expensive and does not need to be called frequently
function userHighRequencyAction(e, content) {
    console.log(e, content);
}

// For the high frequency method, add the anti-shake scheme to output a anti-shake function
var userDebounceAction = debounce(userHighRequencyAction, 1000);

// How to trigger that high frequency function to bind an onMousemove event to simulate high frequency triggering
document.onmousemove = function (e) {
    userDebounceAction(e, 'test debounce'); // Pass a parameter to the shaker function
}
Copy the code
  1. So let’s just write pseudocode first, get our heads together

The basic idea is to use the delay effect of setTimeout WebApi, set a timer, when the delay time is not reached, clear timer (clearTimeout), and set up a new timer, continue to wait for the delay time, and so on.

// Test case
function debounce(func, wait) {
    // Declare a timer
    // We need to return a function closure to save the timer state in memory
    return function () {
        // Time is not up to clear timer
        // Create a new timer
        // Use setTimeout to execute the callback
    };
}
Copy the code
  1. Implement master logic
function debounce(func, wait) {
    // Declare a timer
    let timer; 
    // We need to return a function closure to save the timer state in memory
    return function () {
        // Clear the timer function before the second call
        if (timer) {
            clearTimeout(timer)
        }
        // Use setTimeout to execute the callback
        timer = setTimeout(func, wait);
    };
}
Copy the code
  1. Write down all of these special points, of course, 2,3 you can do it in one step, I’m doing it step by step for example, other complex questions better have a clear step by step.

Points to be improved:

  1. We need to integratethisPoint to the correct object
  2. We have some default parameters that we need to pass to our function, so JavaScript for example provides an event object in our event handler which is (e)
function debounce(func, wait = 1000) { 
    let timer; 
    return function () { 
        // Here we use the lexical scope to save this, passed in the closure, I guess you used that
        let context = this;  
        // So we'll save arguments as well
        let args = arguments;
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(function () {
            // bind this with apply
            func.apply(context, args); 
            // Context.func (args)
        }, wait);
    };
}
Copy the code
  1. The above is almost over, if the interviewer gives you some more extension, just improvise, don’t panic to write better, can’t write down, such as immediate execution, cancel function

Requirement: I don’t want to wait until the event stops firing. I want to execute the function immediately and wait n seconds before I can fire again.

function debounce(func, wait = 1000, immediate = false) {
    var timeout, result;

    var debounced = function () {
        var context = this;
        var args = arguments;
        if (timeout) {
          clearTimeout(timeout);
        }
        // immediate critical changes
        if (immediate) {
            // If yes, no further action is required
            varcallNow = ! timeout; timeout =setTimeout(function(){
                timeout = null;
            }, wait)
            if (callNow) { 
              result = func.apply(context, args)
            }
        } else {
            timeout = setTimeout(function(){
                func.apply(context, args)
            }, wait);
        }
        return result;
    }
    
    debounced.cancel = function() {
        clearTimeout(timeout);
        timeout = null;
    };

    return debounced;
}

// It can be used like this
document.getElementById("button").addEventListener('click'.function(){
    setUseAction.cancel();
})
Copy the code

The userHighRequencyAction function may return a value, so we need to return the result of the function’s execution, but when immediate is false, because setTimeout is used, Apply (context, args) returns the value of func.apply(context, args). The value of func.apply(context, args) will always be undefined, so we only return the result of the function if immediate is true.

5. Function throttle

What is the

In simple terms, we only allow our function to execute once in a specified interval.

For example, if an event is fired crazily and the function should execute hundreds of times per second, but you use the function throttling interval of 1s, the function will only execute once in 1s.

Simple handwriting implementation

implementation

With the anti-shake example above, throttling is simple and works similarly

In simple terms, when the event is raised, a timer is set. When the event is raised again and the timer is present (not null), it is not executed until the function is executed, the timer is null, and the next timer is set. This ensures that the function is executed only once during the wait time.

function throttle(func, wait = 1000) {
    let timer, context, args;
    return function() {
        context = this;
        args = arguments;
        if(! timer) { timer =setTimeout(function() {
                // Execute the post-timer variable to null
                timer = null;
                func.apply(context, args)
            }, wait)
            // func. Apply (context, args) applies immediately}}}Copy the code

If you want to brush the questions with me, you can add me on wechat. Click here to make a friend Or search my wechat account, infinity_9368. You can chat with me and add my secret code “Tianwang Gaidihu”. Verify the message please send me Presious tower shock the rever Monster, I see it through, after adding I will do my best to help you, but pay attention to the way of asking questions, it is suggested to read this article: the wisdom of asking questions

reference

  • Juejin. Cn/post / 689374…
  • Github.com/mqyqingfeng…