What is function stabilization

If a function that was delayed by N seconds is repeatedly fired before execution, the delay is recalculated.

The simplest way to do it

App.vue

<template> <div> < button@click ="debounceTest "> </button> </div> </template> <script> let timerId = null; Export default {methods: {debounceTest(message) {console.log(" The button was clicked... , timerId); if (timerId) { clearTimeout(timerId); timerId = null; } timerId = setTimeout(() => {console.log(" execute the function code: ", message); }, 1000); ,}}}; </script>Copy the code

You can try it, but it’s not reusable, so if another function needs it, you have to rewrite it.

Encapsulate a utility function

App.vue

<template> <div> < button@click ="debounceTest "> </button> </div> </template> <script> import util from './utils' console.log(util) export default { methods: { debounce: Util. Debounce, debounceTest(message) {this.debounce(()=>{console.log(" Execute the anti-shock function code: ", message); }, 2000)()},},}; </script>Copy the code

util.js

let  timerId = null;

function debounce(fn, timerForWait=1000) {
    console.log('Call request initiated');
    return function() {
        if (timerId) {
            clearTimeout(timerId);
        }
        timerId = setTimeout((a)= >{ fn() }, timerForWait); }}export default {debounce};
Copy the code

The way I wrote it up here is a little flawed,

  1. Timers as module internal variables, all functions share a common timer, or can not achieve public.
  2. The way functions are passed as arguments is not very elegant

The final version

util.js

function debounce(fn, timerForWait=1000) {
    console.log('Call request initiated')
    return function() {
        if (fn.timerId) {
            clearTimeout(fn.timerId);
        }
        fn.timerId = setTimeout((a)= > {
            fn(...arguments)
        }, timerForWait);
    }
}

export default {debounce};
Copy the code

App.vue

<template> <div> <button @click="debounce(debounceTest, < button@click =" debounceTest2, debounce1, debounce2 "> </button> </div> </template> <script> import util from './utils' export default { Methods: {debounce: util.debounce, debounceTest(message, time) {console.log(" Execute the anti-shock function code: ", message+time); }, debounceTest2(message, time) {console.log(" execute the anti-shock function 2 code: ", message+time); ,}}}; </script>Copy the code