This is the 4th day of my participation in the August More Text Challenge

Function image stabilization

Function image stabilization is what meaning, such as elevators, in our life. Now you sit elevator door are an infrared ray, after people in the elevator doors shut down in three seconds, and then people behind someone came in again, after in the elevator and wait for three seconds to shut down, that is to say, people go in, and someone came in and then close the behavior of the disappeared, It takes another three seconds to close, and the same logic applies to function stabilization. A function does something, and instead of doing it immediately, it waits for a period of time to do it, and if the condition set during that period of time triggers again, then waits for a period of time. This is called function stabilization. Let’s look at the code.

<body>
    <input type="text">
    <script>
        debounce = function (callback, time) {
            var timer;
            return function (){
                clearTimeout(timer);// Clear the previous timer
                var args = arguments;// Use closures to save parameters
                timer = setTimeout(function(){
                    callback(null,args); },time); }}// Output the search value when the search box stops input for one second
    var inp = document.querySelector("input");
    var handle = debounce(function(val,inp){
        console.log("Search" + inp[0]);
        console.log(inp);
    },1000);
    inp.oninput = function(){
        handle(this.value,this);
    }
    </script>
</body>
Copy the code

In daily use, the search box uses function anti-shake more, the above is the search box function anti-shake code, when the search box stops inputting a second after the output of the search value.

Function of the throttle

Function throttling is a function that executes only once in a period of time and does not re-time. Let’s look at the code.

<body>
    <input type="text">
    <script>
        throttle = function (callback, time) {
            var timer;
            return function (){
                
                if (timer) { // If there is a timer, do not restart the timer
                    return;
                }  
                var args = arguments;// Use closures to save parameters
                timer = setTimeout(function(){
                    callback(null,args);
                     timer = null;// Clear the timer, otherwise it can only run once},time); }}// Output the search value when the search box stops input for one second
    var inp = document.querySelector("input");
    var handle = throttle(function(val,inp){
        console.log("Search" + inp[0]);
        console.log(inp);
    },1000);
    inp.oninput = function(){
        handle(this.value,this);
    }
    </script>
</body>
Copy the code

Above is the code of the search box function throttling, when the search box input output the search value every second.