const throttle = (func, limit) => {
        let lastFunc;
        let lastRan;
        return function() {
          const context = this;
          const args = arguments;
          if (!lastRan) {
            func.apply(context, args);
            lastRan = Date.now();
          } else {
            clearTimeout(lastFunc);
            lastFunc = setTimeout(function() {
              if ((Date.now() - lastRan) >= limit) {
                func.apply(context, args)
                lastRan = Date.now()
              }
            }, limit - (Date.now() - lastRan));
          }
        }
      }
      Javascript language logo

      Throttling in Javascript

      rate-limit
      throttling
      javascript

      This code creates a throttle function that looks for a function called lastFunc and sets a timeout so that lastFunc will be executed after a certain amount of time has passed. The limit parameter is used to determine how long the timeout will last.

      Shortcut: throttle

      0 Comments

        Add Comment

        Log in to add a comment

        Codiga - All rights reserved 2022.