This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

☀ ️ preface

  • Some time agoGroup of friendsI always get mixed up in interviewsImage stabilizationandThe throttle.
  • Actually,Image stabilizationandThe throttleNot only in the interview will ask people to write, in the actual project can also play a role in performance optimization, so it is very necessary to master.
  • I’m going to take you through handwriting over a cup of teaImage stabilizationandThe throttle.

🍀 stabilization

🌰 for example

  • Concepts aside, there are many in lifeImage stabilizationExample:
    • The computer you’re using now, for example, automatically sleeps for a period of time when you’re not using it
    • Reactivate when you use it again and start counting down the time you set10minutes
    • In this10If you continue to use the computer within a minute, the countdown will start again10minutes
    • Restart the countdown when you use your computer for the last time and leave10Minutes passed and the computer went to sleep

  • In fact, this is the basic concept of anti – shake ~ to put it bluntly is only executed once in a period of time, that is, we only open the computer this time.
  • Our use of computers above can be understood asTriggering eventAnd what I marked abovesetTimeoutandclearTimeoutIn fact, it is the main element of anti-shake.
  • Of course, the above is the example in life, that we often use in our daily development, such as we adjust the size of the page, verify whether a field is repeated request times control, prevent form multiple submission, etc.

✍️ Handwriting anti-shake

  • Having said so much, I believe you probably understandImage stabilizationSo let’s implement one nowImage stabilizationWell, suppose we were to click on a button to add a message, and of course weYou don’t want to call interface additions every time you click, we want multiple clicksAdd it once onlyWhat should we write?

  • Let’s start by simply simulating the process of a button being clicked.
// debounce.js
let addBtn=document.getElementById('add')
function addOne(){
  console.log('Add one')
}
addBtn.addEventListener('click',addOne)
Copy the code
  • Because we need to handle the events that are executed, we need to encapsulate themaddOneFunction.
// debounce.js
let addBtn=document.getElementById('add')
function addOne(){
  console.log('Add one')}function debounce(fun){
  return function(){
    fun()
  }
}
addBtn.addEventListener('click',debounce(addOne))
Copy the code
  • We did that with closures up hereaddOneFunction, next we need to add a delay timersetTimeoutTo count down when we click the button2sTo perform again.
// debounce.js
function debounce(fun,time){
  return function(){
    setTimeout(() = >{
      fun()
    },time)
  }
}
addBtn.addEventListener('click',debounce(addOne,2000))
Copy the code
  • Now, the purpose of the delay is done but every time you click on it, you’re adding a new onesetTimeoutAnd it’s not going to be the same as if we clicked once.
  • That’s when you needclearTimeoutHere we go. What we need is after we click the button which isdebounceI’m going to execute the previous onesetTimeoutClear it and then reset the timer.
function debounce(fun,time){
  let timer
  return function(){
    clearTimeout(timer)
    timer=setTimeout(() = >{
      fun()
    },time)
  }
}
Copy the code
  • Now we have one of our anti-shake features, but that’s not all, if we’re inaddOne()printthisWe’re going to find ourselves doing thisthisIs pointing toWindow.
  • This is certainly not what we want, we need to useapplyTo change thethisThe second is that we need to take into account the arguments that execute the function, because different functions will certainly have different arguments that we can use for argumentsargumentsTo deal with.
function debounce(fun,time){
  let timer
  return function(){
    clearTimeout(timer)
    let args = arguments
    timer=setTimeout(() = >{
      fun.apply(this,args)
    },time)
  }
}
Copy the code
  • So that ourImage stabilization functionI wrote it by hand, and it didn’t look that hard.
  • In a nutshellImage stabilizationIt’s in constant action (typing, clicking, etc.)A method to improve performance that is ultimately executed only once.

🍁 throttling

🌰 for example

  • Of course, there are many examples of saving money in our daily life. I don’t know if you have ever noticed the sprinklers in the park:
    • We usually make a time assumption for the sprinklers30min
    • When the time since the last sprinkling is not enough30minRemain at rest all the time
    • And when the30minWill trigger the watering event

  • This is actually the most basic concept of throttling, which is to perform it at intervals
  • Our sprinklers can be interpreted as triggering events, and the rest of the information we’ve labeled is just that30minAnd the current time, these are the main elements of throttling.
  • Of course, the above is the example in our life, we also often use it in our daily development, such as we scroll the mouse wheel to monitor the position of the scroll bar, to prevent the button from clicking many times.

✍️ handwritten throttle

  • Having said so much, I believe you probably understandThe throttleSo let’s implement one nowThe throttleLet’s say we now want to implement a mouse scroll print event,Want to let it in3sPerform aWhat should we write?

  • First let’s simulate a trigger event.
// throttle.js
function scrollTest(){
  console.log('Now I've triggered it.')}document.addEventListener('scroll',scrollTest)
Copy the code
  • Next we encapsulate a throttling function. Just like the anti-shock function, we also need to use the closure and add a parameter to receive the throttling time.
// throttle.js.function throttle(fun,time){
  return function(){
    fun()
  }
}
document.addEventListener('scroll',throttle(scrollTest,3000))
Copy the code
  • Because our throttling is performed once in a period of time, that is, if the time between the two mouse scrolls does not reach the set time, it will not be performed.
  • Well, we can record the time stamps of each scroll to compare.
// throttle.js.function throttle(fun,time){
  let t1=0 // The initial time
  return function(){
    let t2=new Date(a)// The current time
    if(t2-t1>time){
      fun()
      t1=t2
    }
  }
}
Copy the code
  • We’re going to record two times one ist1That’s the initial time, one ist2Represents the current time if the current time is greater than the previous time (the initial time)time.
  • Then we can do itfun()And change the initial time to the time of this execution, so that every time after we executet1This becomes the last time it was executed.
  • This completes one of our throttling functions.
// throttle.js.function throttle(fun,time){
  let t1=0 // The initial time
  return function(){
    let t2=new Date(a)// The current time
    if(t2-t1>time){
      fun()
      t1=t2
    }
  }
}
Copy the code
  • Of course, we need to change as wellthisPoint to and receive parameters, and when you’re done, it looks like this.
// throttle.js.function throttle(fun,time){
  let t1=0 // The initial time
  return function(){
    let t2=new Date(a)// The current time
    if(t2-t1>time){
      fun.apply(this.arguments)
      t1=t2
    }
  }
}
Copy the code
  • At this point a throttling function is written by hand, isn’t it too difficult?
  • In a nutshellThe throttleIs in theA method of improving performance by performing operations over a period of time but only once in a specified period of time

👋 is at the end

  • First of all, thank you very much for reading here. This article is shared here ~
  • forImage stabilizationandThe throttleOne of the most subjective ways to judge is: in10sWithin youClick a button crazilyIf usedAnti-shake will only be performed once“And you used itThrottling is performed at regular intervalsThis is a time you can control yourself.
  • Of course,Image stabilizationandThe throttleThere are still a lot of transformations, depending on different needs to transform different functions butAll changes are inseparableOnce you understand the above method, the rest is ok.
  • If you feel that this article has helped to your words might as well 🍉 attention + likes + favorites + comments + forward 🍉 support yo ~~😛 your support is the biggest power OF my update.
  • If you want to discuss with me and learn more about the front end you can join meFront-end communication learning group, we talk about the world ~~~

🌅 past wonderful

Byte don’t send mooncakes to everyone? 🎑 that I personally hair to everyone! 🥮 Everyone has it!

Draw 5 pictures to help you beat dynamic permission routing easily!

Product Manager: Can you get the word cloud moving?

Fix echarts map rotation highlighting ⚡