Matt's 411

A Web Developer's Blog · Javascript, CSS, HTML and more

  • Delaying Javascript Event Execution

    Monday, October 13, 2008·Share
    • Facebook
    • ·
    • Google Plus
    • ·
    • LinkedIn
    • ·
    • StumbleUpon
    • ·
    • Twitter
    ·Comments

    If you're looking to execute javascript code whenever someone finishes (or stops temporary) scrolling, moving the mouse, or resizing the page, you may find the following code segment useful.

    var onFooEndFunc = function() {
      var throttleTimer;
      return function(event) {
        throttleTimer = (!!throttleTimer) ? window.clearTimeout(throttleTimer) : null;
        throttleTimer = window.setTimeout(function() {
          
          // Your code here
          
        }, 50);
      };
    }();
    

    As an example, let's say you have an element with ID "foobar" and you want to perform some action on scroll, but only when the user stops scrolling. You can do this by creating the function above and assigning it to the element's onscroll event handler:

    document.getElementById("foobar").onscroll = onFooEndFunc;
    

Latest Posts

  • Internet Explorer localStorage polyfill using userData
  • Autocomplete with <datalist>
  • Internet Explorer 9 oninput event
  • Grid Updated
  • Canvas Pie and Ring Charts with Tooltips
  • Receive an SMS via Twilio When Your Website Goes Down
  • Comments with Disqus.com
  • Disabling Spellcheck in Textarea Elements
  • Setting the name attribute in IE's DOM
  • Recent Activity
  • Tips for Web Developers
  • Delaying Javascript Event Execution
  • Auto Selecting HTML Text with Javascript