Nonvoluntary Professional Mangling
    Have ideas to improve npm?Join in the discussion! »

    throttle-frequency

    1.0.4 • Public • Published

    Throttle Frequency

    Simple vanilla JavaScript tool to throttle execution frequency of any given function - time in milliseconds, no initial delay, optional scope declaration.

    Installation

    Install via npm

    $ npm install throttle-frequency

    ... or yarn

    $ yarn add throttle-frequency

    then require

    var throttleFrequency = require('throttle-frequency');

    or import

    import throttleFrequency from 'throttle-frequency'

    Usage

    throttleFrequency(func, delay, scope);

    • param {function} func - function to execute
    • param {number} delay - delay in milisecionds
    • param {object} scope - optional scope in which function will be executed
    • return {function} - wrapped func

    Examples

    Throttling variable manipulation:

    var test;
    var testFunc = function(arg) { test = arg; };
    var testFuncThrottled = throttleFrequency(testFunc, 500);
     
    testFuncThrottled('TEST 1!');
    console.log(test); // 'TEST 1!'
     
    setTimeout(function() {
      testFuncThrottled('TEST 2!');
      console.log(test); // (after 501 ms) 'TEST 2!'
    }, 501);
     
    testFuncThrottled('TEST 3!');
    console.log(test); // 'TEST 1!'

    Emitting debounced window resize event - a little bit more practical example

    var triggerEvent = function(name, data) {
      var newEvent = document.createEvent('Event');
      newEvent.initEvent(name, true, true);
      newEvent.data = data;
      window.dispatchEvent(newEvent);
    };
     
    var debounceEvent = function(opts) {
      var wrappedEvent = function(event) { triggerEvent(opts.name, event); };
      var debounced = throttleFrequency(wrappedEvent, opts.delay);
      opts.element.addEventListener(opts.type, debounced);
    };
     
    debounceEvent({
      element: window,
      type: 'resize',
      name: 'debouncedResize',
      delay: 800
    });
     
    window.addEventListener('debouncedResize', function(event) {
      console.log(event); // returns original 'resize' event object
      console.log('Width: ' + window.innerWidth + ' Height: ' + window.innerHeight);
    });
     

    Author

    Kuba Paczyński

    License

    Copyright © 2017, Kuba Paczyński. Released under the MIT License.

    Install

    npm i throttle-frequency

    DownloadsWeekly Downloads

    1

    Version

    1.0.4

    License

    MIT

    Last publish

    Collaborators

    • avatar