Skip to Content

throttle()

Limits an event to only happen once per a set amount of time.

JavaScript June 30, 2020

Usage

JavaScript
nebula.throttle(callback, cooldown, uniqueId)

Parameters

callback
(Required) (Function) The function to run after the wait period
Default: None

cooldown
(Required) (Integer) How long (in milliseconds) between callback calls
Default: None

uniqueID
(Optional) (String) A unique ID to separate different Debounce function calls
Default: "Don't call this twice without a uniqueId"

Request or provide clarification »

Examples

Window resize

JavaScript
jQuery(window).on('resize', function(){
    nebula.throttle(function(){
        //This happens every 500ms while the window is resizing
    }, 500, 'user resizing window');
});

Remember that the scope of "this" changes inside of the throttle function!

JavaScript
jQuery('#s').keyup(function(){
    var oThis = jQuery(this); //Store "this" in an object to pass into the throttle
    
    nebula.throttle(function(){
        //jQuery(this) now refers to the throttle function- not the input!
        var inputValue = oThis.val();
    }, 1500, 'user typing in search');
});

Additional Notes

Very similar to debounce but where debounce happens only once at the end (or the beginning), throttle happens multiple times but limited to a set amount of time in between.

Source File

Located in /assets/js/nebula.js on line 4017.

JavaScript
nebula.throttle = function(callback, cooldown, uniqueID){
    if ( typeof nebula.throttleTimers === "undefined" ){
        nebula.throttleTimers = {};
    }

    if ( !uniqueID ){
        uniqueID = "Don't call this twice without a uniqueID";
    }

    var context = this;
    var args = arguments;
    var later = function(){
        if ( typeof nebula.throttleTimers[uniqueID] === 'undefined' ){ //If we're not waiting
            window.requestAnimationFrame(function(){
                callback.apply(context, args); //Execute callback function

                nebula.throttleTimers[uniqueID] = 'waiting'; //Prevent future invocations

                //After the cooldown period, allow future invocations
                setTimeout(function(){
                    nebula.throttleTimers[uniqueID] = undefined; //Allow future invocations (undefined means it is not waiting)
                }, cooldown);
            });
        }
    };

    return later();
};

Override

To override or disable this JavaScript function, simply redeclare it with the exact same function name.

JavaScript
nebula.throttle = function(callback, cooldown, uniqueID){
    //Write your own code here, leave it blank, or return false.
}