[Help] the front of the 7 understanding on the throttle (throttle) and image stabilization (debounce) of

Throttle and stabilization in our usual projects very common, but also interview will often be a question of knowledge, today we are together to learn about.

Throttling

Simple to understand: the control function executed once every n seconds.

effect

Prevent high frequency users trigger event, just the event they need to handle a large number of calculations and rendering brought performance issues.

Scenarios

  • onscroll
  • OnResize
  • mousemove
  • touchmove
  • ...

Examples

Here we have to onscrollwrite an example, to deepen understanding.

For example, there is a scenario: we need to determine the browser scroll bar to scroll in the end part of the time to dynamically load some data, perhaps we will direct and write the following code:

let obj = document.querySelector('.throttle-test');
let _count = 0;

obj.onscroll = function () {
  // 假设已经滚动到底部了,我们给_count加1。
  _count++;
  console.log('执行次数:' + _count);
}
复制代码

We look at the results of the browser's print, gif see the following chart:

You can see, the function carried out 20, it is clear that this is not what we want, because onscrollthe event will not wait for you to go rolling in the end part of the triggering event, but will be uninterrupted trigger, which can easily lead to some performance issues, this time we need to use the throttle.

We modify the code to do next:

let obj = document.querySelector('.throttle-test');
let _count = 0;
let _canRun = true;
obj.onscroll = function () {
  if (!_canRun) {
    return false;
  }
  _canRun = false;
  setTimeout(function () {
    // 假设已经滚动到底部了,我们给_count加1。
    _count++;
    console.log('执行次数:'+_count);
    _canRun = true;
  }, 500);
}
复制代码

Gif by the following chart, we can see that the ultimate function is performed only twice.

By a timer, we have the control function is performed once every 500 milliseconds then, greatly reducing the execution frequency, so as to enhance performance.

Throttle conceptual understanding

Throttle with image stabilization, they have similarities but different, it is easy to confuse. Here to deepen understanding through metaphor, first is that the throttle.

The concept throttling can imagine dams you build a dam in the river, can not let the water flow can not, you can let the water slowly. In other words, you can not make the user's methods are not implemented. (Personally like this metaphor because it is the image of say the difference with image stabilization.)

Shake

Control functions within n seconds can only be executed once, if the user repeats in n seconds trigger event, and then re-timing function will not be executed only when the user no longer wait until a trigger event before going to execute once.

Action with 节流a similar, but also to prevent performance problems users high frequency triggering event triggered.

Image stabilization conceptual understanding

Imagine doing the elevator when someone entered the elevator (the triggering event), and that the elevator will start after 10 seconds (execution event), then if someone enters the elevator (in 10 seconds once again triggered the event), we have again in 10 seconds to trigger (re-timing).

Examples

There is a text box to let the user fill in user name, when the user enters a character, we need to send a request to the background in real time to verify whether there are duplicate user name. In fact, before joining the anti-shake mechanism, the user input helloworld, we have sent 10 requests, it is clearly undesirable.

Look at the code:

let obj = document.querySelector('#testInput');  // 获取文本输入框
let _count = 0;

obj.onkeyup = function () {
  _count++;
  console.log('执行次数:' + _count);
}
复制代码

We give the code to join the anti-shake mechanism:

We can only assume that the user no longer trigger events in pause n seconds, we determined that the user has entered is complete, the next time you send a request.

Look at the code:

let obj = document.querySelector('#testInput');
let timer = null;
let _count = 0;

obj.onkeyup = function () {
  clearTimeout(timer);  // 清除定时器,重新计时
  timer = setTimeout(function () {
    _count++;
    console.log('执行次数:'+_count);
  }, 800);
}
复制代码

By moving map, you can see, when I have been input, the event will not be triggered until I stop input will trigger once.

Realization of ideas: we have to put a timer object code, if an event is frequently triggered object code will not be executed. Why not enforce it, because we've added clearTimeout. It was the equivalent of halfway continued into the elevator, the elevator and have to re-start the countdown 10 seconds before the same until the user did not re-enter the (no one will enter the elevator), this time the object code only in accordance with our set time to go execution time (elevator will not start).

The difference between the throttle and image stabilization

  • Throttling: we set the target code according to a time interval that is executed once every n seconds
  • Image Stabilization: When the user does not trigger the event, before going to execute the object code, and inhibits the action would have to be executed in the event; in the case where an event has been triggered, the object code likely will not be executed
  • Throttle function will be used in the ratio input, keyupthe event triggered more frequently, such as resize, touchmove, mousemove, scroll. 节流Forcing function will be performed at a fixed rate. Therefore, this method is suitable for scenarios used in the animation-related.

At last

Thanks for reading, I hope for your help. If you have a local paper described inappropriate, please correct me, very grateful. Also herein demonstrate the use of the code used to test only, not suitable for use in the actual development, the actual development can use the Lodashlibrary 节流and 防抖methods, not posted the code here, after all, more comprehensive consideration of Kazakhstan.

LodashLibrary Address:

Throttling: www.lodashjs.com/docs/4.17.5...

Image Stabilization: www.lodashjs.com/docs/4.17.5...

attention

I welcome everyone's attention the public number 前端帮帮忙, together with the exchange of learning, thank you ~

Reference: zhuanlan.zhihu.com/p/38313717

Guess you like

Origin blog.csdn.net/weixin_34314962/article/details/91364398