debounceer

1.0.8 • Public • Published

Debounce Function vs Throttle Function

Install

npm i debounceer

Debounce Function

Usage

Usage in vue components

import {debounce} from 'debounceer';
export default {
    setup(){
        // call the debounce function
        const handler= debounce(function{
                alert('do sth')
        })
        return {
            handler
        }
    },
    methods:{
        // call the debounce function
        handler2:debounce(
            function(){
                alert('do sth')
            }
        )
    }    
}

Debounce Function Source

export function debounce(fn, timeout = 200) {
    // Save the timer id.
    var timer;
    return function (...args) {
        // Save the this object
        const that = this;
        // If the timer is exist
        timer > 0 && clearTimeout(timer)
        // Restart the timer
        timer = setTimeout(() => {
            // Call the function some seconds later
            fn && fn.apply(that, args);
        }, timeout);
    }
}

Throttle Function

Usage

import {throttle} from 'debounceer';
export default {
    setup(){
        // call the throttle function
        const handler=throttle(function(){
                alert('do sth')
            })
        return {
            handler
        }
    },
    methods:{
        // call the target function some seconds later
        handler2:throttle(
            function(){
                alert('do sth')
            }
        )
    }
}

Throttle Function Source

// Throttle Function
// fn:  The function will be called.
// time: The delay time.
export function throttle(fn, timeout = 150) {
    // Save the timer id
    var timer;
    return function (...args) {
        // If the timer is exist
        if (!timer) {
            // Save the this object
            var that = this;
            // Start the timer
            timer = setTimeout(() => {
                //Call the function some seconds later
                fn && fn(that, args);
            }, timeout);
        }
    }
}

Friend Links

Readme

Keywords

none

Package Sidebar

Install

npm i debounceer

Weekly Downloads

2

Version

1.0.8

License

ISC

Unpacked Size

3.66 kB

Total Files

3

Last publish

Collaborators

  • thegirlwiththebox