Page Content

Tutorials

What are the Throttling Events in jQuery With Code Example

Throttling Events in jQuery

Throttling Events
Throttling Events

Events like scroll, resize, and mousemove occur often, hence event throttling events is necessary to limit event handler execution. These “performance-sensitive” events may be triggered quickly and repeatedly in some browsers, which can increase processing effort and user performance.

The main goal of throttling events is to make sure that costly computations or actions related to an event handler only take place after certain event occurrences, as opposed to on each and every one. Whereas the handler fires as frequently as the event is noticed, immediate execution is the opposite. Controlling execution frequency reduces system and browser burden, improving web application responsiveness and user experience.

Implementing Throttling

The setTimeout function in JavaScript combined with a timer or flag variable is a popular and efficient way to do event throttling. By delaying its execution, this method guarantees that the costly function operates at a regulated pace.

This method is explained in full below, with an example of code showing how to throttle a scroll event handler:

Code Example:

<!DOCTYPE html>
<html>
<head>
  <title>Throttled Scroll</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    #container { height: 1500px; background: #e0f7fa; padding: 20px; }
    #log { position: fixed; top: 10px; left: 10px; background: #fff; padding: 5px; #ccc; }
  </style>
</head>
<body>
<div id="log">Scroll down...</div>
<div id="container">
  <h2>Scroll Example</h2>
  <p>Scroll to the bottom to see throttled output.</p>
</div>
<script>
  (function($) {
    var timer = 0;
    function checkScrollPosition() {
      var scrollPos = $(window).scrollTop() + $(window).height();
      var containerHeight = $('#container').height();
      if (scrollPos >= containerHeight) {
        $('#log').text('Bottom reached! Loading more...');
        console.log('Loading more content...');
        $(document).trigger('nextPage');
      }
    }
    $(window).on('scroll', function() {
      if (!timer) {
        timer = setTimeout(function() {
          checkScrollPosition();
          timer = 0;
        }, 250);
      }
    }).trigger('scroll');
    $(document).on('nextPage', function() {
      console.log('Custom event triggered: nextPage');
    });
  })(jQuery);
</script>
</body>
</html>

Output:

Bottom reached! Loading more...
Scroll Example

Scroll to the bottom to see throttled output.

Explanation of the Throttling Mechanism

var timer = 0;: Keeps the ID returned by setTimeout . The initialisation to 0 (or null) indicates no function execution is scheduled.

$(document).ready(function() { … });: This jQuery standard ensures code runs only when the DOM is fully loaded and ready for interaction. Due to browser incompatibilities, this is more trustworthy than window.onload.

$(window).scroll(function() { … });: This line assigns an anonymous function to handle the window object’s scroll event. Continuous scrolling triggers this handler repeatedly.

if (!timer) { … }: To handle scroll events, the code first checks if the timer is 0. If so, no checkScrollPosition call is queued. A non-zero timer indicates an active setTimeout for checkScrollPosition. The block’s code is skipped because the if condition is false. This avoids repeatedly calling the expensive checkScrollPosition method during a quick scroll.

timer = setTimeout(function() { … },: The checkScrollPosition() function is inside an anonymous function supplied to setTimeout. It delays execution for 250 milliseconds. The timer receives the ID supplied by setTimeout, indicating a planned execution.

timer = 0;: After checkScrollPosition executes (i.e., setTimeout fires), timer is reset to 0. This restores throttle, allowing a new checkScrollPosition execution after 250ms if the scroll event persists.

.trigger(‘scroll’);:After setting up the handler, this line fires the scroll event. This can help with infinite scrolling, when initial material must load or position correctly on page load without user involvement.

The checkScrollPosition function, which may check scroll positions and trigger AJAX requests, is executed once every 250 milliseconds instead of on every scroll event, improving performance and user experience.

Benefits and Considerations

Significant Performance Improvement: This method significantly lowers the frequency of the costly checkScrollPosition function’s execution. It runs a few times inside the designated intervals rather than hundreds of times during a quick scroll.

Smoother User Experience: The smooth user experience is a good balance between little performance impact and immediate response. Although the browser doesn’t slow down, the user feels responsive.

Adjustable Delay: The 250 millisecond delay can be adjusted to suit your application and perceived responsiveness.

Common Use Cases: Mousemove, resize, and scroll are good targets for this throttling events . Mobile context scrollstart and scrollstop events are supplied in jQuery Mobile applications, and scrolling on mobile devices frequently has a “eased” effect, which slows down over time. Particularly useful in mobile contexts with relatively limited is throttling events .

Other Throttling and Debouncing Techniques

Although many people use the setTimeout with timer method:

setInterval with a Flag (Polling): A different approach is to use setInterval and a scrolling boolean flag. After the event handler sets the scrolled flag to true, it is continuously checked by a different setInterval. Should scrolling be true, the costly function executes and the flag is changed back to false. The answer here is a “polling” one.

Debouncing: Although it has a similar function to throttling events , debouncing makes sure that a function is only run after a predetermined amount of idleness. You could wish to send an AJAX request, for instance, only after the user has stopped typing for a few hundred milliseconds, rather than on each keyup event, in a live search function. This keeps a deluge of requests from coming in while the user is typing. Setting and clearing timeouts is common in debouncing.

Throttling events can make web apps more responsive and resilient, reduce performance degradation from frequent throttling events, and improve user experience.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index