preface

Recently at home work a little spare, brush some of the front end test questions, study function throttling and function anti – shake. This thing is also commonly used in the project, but has been directly copy code from the Internet, without in-depth study, recently looked carefully, or a bit of harvest, when the front-end interview, often asked about closure knowledge, throttling and anti-shock is a very classic closure application.

scenario

Common scenarios for throttling

In everyday development, we might come across a scenario where the width and height of an element changes as the window changes; Such as: When we use the element-UI table component, the table’s data is indestructible, but we need to fix the table header, and we need to provide a specific height for the component when there is too much content to scroll through, but the browser window width is variable (to artificially zoom the browser). This requires us to listen for window changes, and when the window width and height change, execute a function that recalculates the browser width and height to make the table height change

Anti-shake common scenarios

In daily development, we might encounter real-time search scenarios; For example: the user entered the content in the search box, we should recommend the relevant search language to the user in real time according to the content, let the user choose.

The problem

In the above two scenarios, have one thing in common is the function is called high frequency, whether real-time window changes or real-time input box changes, will trigger the resize and input of uhf events, but the difference is that in throttling scenario, we more hope is in a certain period of time, calculating window width high function is executed only once; In the anti-shake scenario, we prefer to recommend search terms to users based on the input content after the user enters.

The solution

Throttling code solution

For throttling scenarios, the goal is to execute functions only once in a certain period of time; We assume that the browser width is calculated every 200 milliseconds during the window change, that is, the element size is changed every 200 milliseconds


const getWindowHeight = (a)= > {
  const {width,height} = window.screen;
  console.log('Browser width:',width, 'Browser height is :', height);
}
// Calculate the window width and height change
const throttle = (fn) = > {
  let timeNo;
  return (a)= > {
  	console.log('Window change');
    if(timeNo) return;
    timeNo = setTimeout((a)= > {
      fn()
      clearTimeout(timeNo);
      timeNo = null;
    }, 200); }}// Listen for window width and height changes
window.addEventListener('resize', throttle(getWindowHeight))

Copy the code

Anti – shake code solution

For the anti-shake scenario, our goal is to execute the function with the last trigger when the high frequency is triggered; We assume that the interval is 200 milliseconds, that is, after the user enters something in the search box and triggers the input event, we wait 200 milliseconds to retrieve the content of the input box. Within 200 milliseconds after the user enters something, we wait again.

const input = document.querySelector('#input'); // Take the input field object
const debounce = (a)= > {
  let timeNo;
  return (e) = > {
    clearTimeout(timeNo);
    timeNo = setTimeout((a)= > {
      const {target: {value}} = e;
      console.log('Input field value is',value)
      clearTimeout(timeNo);
    },200)
  }
}
input.addEventListener('input', debounce()); // Listen for input events in the input box
Copy the code

concept

Function throttling refers to the execution of a function at a fixed interval during a continuous firing of an event.

Function stabilization is the execution of a function only on the last firing of an event in succession

To optimize the

Generic encapsulation of function throttling

/** @param {function} fn - calls to be executed, calls to be executed * @param {number} Intervals - calls to be executed * @params {any} args - The remaining parameters will be passed to fn * @params {any} params when fn is called. An event object will be passed, so you also need to receive * @return function */
const throttle = (fn, Intervals, ... args) = > {
  let timeNo;
  return (. params) = > {
    if(timeNo) return;
    timeNo = setTimeout((a)= >{ fn(... args,... params) clearTimeout(timeNo); timeNo =null; }, Intervals); }}// Use examples
const obj = {
  name: 'Joe',
  fun(params, str) {
    console.log(this.name, 'Receive parameters', params, str); }}window.addEventListener('resize', throttle(obj.fun.bind(this), 200, {text: 'First argument passed out'}, 'Outermost second argument'))
Copy the code

General purpose package for function stabilization

/ general version of the image stabilization function * * * * * @ param {function} fn - to be performed, how long does it take to be executed apart method * @ param {number} Intervals - time interval, * @params {any} args - Residual arguments that will be passed to fn * @params {any} params - When the input event is triggered An event object will be passed, so you also need to receive * @return function */
const debounce = (fn, Intervals, ... args) = > {
  let timeNo;
  return (. params) = > {
    clearTimeout(timeNo);
    timeNo = setTimeout((a)= >{ fn(... args,... params) clearTimeout(timeNo); }, Intervals) } }// Use examples
const getInputValue = (e) = > {
  const {target: {value}} = e;
  console.log('Input field value is',value)
}
const input = document.querySelector('#input'); // Take the input field object
input.addEventListener('input', debounce(getInputValue,200)); // Listen for input events in the input box
Copy the code

Next article: Customizing vuE-CLI project templates

Iframe architecture micro front-end practice said, in order to facilitate the new project, the parent project and sub-project can be made into a Vue template, using VUE-CLI to create a project directly to pull the specified template, save the process of modification, directly out of the box, the next article plans to write how to customize the Vue project template.

series

Iframe architecture micro front-end combat

Nginx common configuration

Structural design of large front-end projects

Git management scheme for large front-end projects

How to significantly improve front-end loading performance

Installing nginx on Linux

How to implement a message prompt component (Vue) using JS calls