define

Stabilization:

If the event is triggered again within a certain period of time, the event will be cleared and started again. If the event is not triggered again within the specified period of time, the event will be executed.

Throttling:

Throttling means that the same event will only be triggered once at a certain time and will only be triggered again after this time.

Usage scenarios

  • The search box
  • button
  • Monitor the scroll
  • Frequent Mouse use
  • .

In summary: anything that is called frequently may need to be optimized for stabilization or throttling

implementation

Image stabilization

	function showLog() {
        console.log('show');
    }

    /* * Start a scheduled task first, and clear it after the scheduled task is completed; If the scheduled task still exists, the system clears the original task and creates a new scheduled task * */
    function debounce(fn, space) {
        let task = null;
        return function (){
            if(task) {
                clearTimeout(task);
            }
            task = setTimeout(fn.apply(this.arguments), space); }}/ / use
    let debounceShowLog = debounce(showLog, 3000);
    debounceShowLog()
Copy the code

The throttle

 /* * Throttling idea: * First start a scheduled task execution, the scheduled task is cleared after completion, when called, if the scheduled task still exists, no operation is performed * */
    function throttle(fn, space) {
        let task = null;
        return function () {
            if(! task) { task =setTimeout(function () {
                    task = null;
                    fn.apply(this.arguments); }, space); }}}let throttleShowLog = throttle(showLog, 3000);
Copy the code

Simplicity is love