Skip to Content
Menu

throttle()

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

JavaScript February 7, 2021

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: 1000

uniqueID
(Optional) (String) A unique ID to separate different Debounce function calls
Default: "No Unique ID"

Request or provide clarification »

Examples

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');
});

Throttle a function and then run it once again at the end (regardless of when it happens in relation to the cooldown)

JavaScript
jQuery(window).on('resize', function(){
    nebula.throttle(function(){
        doTheThing(); //This happens every 500ms while the window is resizing (but probably not at the very end)
    }, 500, 'user resizing window');

    nebula.debounce(function(){
        doTheThing(); //This happens only once after the event ends
    }, 500, 'user resizing window');
});

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.

Remember: there is no guarantee that an event will trigger at the end! If the action being throttled stops half-way into the cooldown, it will not trigger again! For example, when throttling a window resize in 1 second intervals to detect media queries, you could end up with an incorrect detection if the user quickly changes their screen size in less than 1 second (or if it ends in-between the 1-second cooldown after going beyond the media query threshold).

If you need an event to happen at the end, you’ll need to use debounce. This can be done in addition to throttling, though!

Was this page helpful? Yes No


    A feedback message is required to submit this form.


    Please check that you have entered a valid email address.

    Enter your email address if you would like a response.

    Thank you for your feedback!

    Source File

    Located in /assets/js/modules/utilities.js on line 514.

    No Hooks

    This function does not have any filters or actions available. Request one?
    JavaScript
    nebula.throttle = function(callback, cooldown = 1000, uniqueID = 'No Unique ID'){
        if ( !callback ){
            nebula.help('nebula.throttle() requires a callback function.', '/functions/throttle/');
            return false;
        }
    
        nebula.throttleTimers = nebula.throttleTimers || {};
    
        const later = () => {
            if ( !nebula.throttleTimers[uniqueID] ){
                window.requestAnimationFrame(() => {
                    callback.apply(this, arguments); //Execute the callback function
    
                    nebula.throttleTimers[uniqueID] = true; //Prevent future invocations
    
                    //After the cooldown period, allow future invocations
                    setTimeout(() => {
                        nebula.throttleTimers[uniqueID] = false;
                    }, cooldown);
                });
            }
        };
    
        return later();
    };
    

    Override

    To override or disable this JavaScript function, simply redeclare it with the exact same function name. Remember: Some functionality is conditionally loaded via dynamic imports, so if your function is not overriding properly, try listening for a DOM event (described below).

    JavaScript

    For non-module import functions:

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


    For dynamically imported module function overrides:

    jQuery(window).on('load', function(){
        nebula.throttle = function(callback, cooldown, uniqueID){
            //Write your own code here, leave it blank, or return false.
        }
    });


    Custom Nebula DOM events do also exist, so you could also try the following if the Window Load listener does not work:

    jQuery(document).on('nebula_module_loaded', function(module){
        //Note that the module variable is also available to know which module specifically was imported
        if ( typeof nebula.throttle === 'function' ){
            nebula.throttle = function(callback, cooldown, uniqueID){
                //Write your own code here, leave it blank, or return false.
            }
    	}
    });