QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads JavaScript Limit Function Call Rate

JavaScript Limit Function Call Rate

Sometimes its necessary to limit the number of times a function can be fired in an second, minute or hour. If a function does some heavy frontend reflow or repainting or else sends/receives data from server then its better to limit the number of times it can execute in a given amount of time.

JavaScript developers usually use a hack i.e., wrapping a normal function in an debounce function. Debounce function is a wrapper and it decides weather the actual code of the function should be executed or not at a particular given time.

Here is code for creating a debounce function i.e., function call rate limiting wrapper function

function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this,
            args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

Here is an example of how debounce function controls the call rate of an normal function

In the above example the setTimeout callback was supposed to run after 100ms when button is clicked but debounce functions queues it to execute after 5sec. And any number of calls during queue is cancelled.

Jan 29, 2015Narayan Prusty
Facebook Style Face Detection and Tagging with JavaScriptTyping Effect using JavaScript

Leave a Reply Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Narayan Prusty

I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

8 years ago Web Development
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
Related Articles
  • JavaScript “class” Keyword
  • Measure Web Page Performance Using JavaScript
  • Increase PHP Script Execution Time
  • Page Visibility API Tutorial with Example
  • Web Alarms API Tutorial
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license