38

Possible Duplicate:
Throttle event calls in jQuery

I like the .change() functionality of jQuery, but I'd like to prevent triggering a ton of AJAX requests when a user quickly changes options in a select drop down. As an example, when a user uses a mouse scroll wheel, it will trigger each options as they pick their new option.

I'd like to come up with a good clean way to handle only sending these updates once the user stops updating the select dropdown a second.

Is there a neat way of handling this situation?

Community
  • 1
  • 1
GoldenNewby
  • 4,382
  • 8
  • 33
  • 44

2 Answers2

103

The typical way to do this is with a setTimeout and clearTimeout:

var wto;

$('#select').change(function() {
  clearTimeout(wto);
  wto = setTimeout(function() {
    // do stuff when user has been idle for 1 second
  }, 1000);
});
glortho
  • 13,120
  • 8
  • 49
  • 45
  • 3
    What does wto stand for? – Gisheri Aug 14 '15 at 15:19
  • 1
    Window.TimeOut - just random choice for example. – glortho Aug 14 '15 at 15:48
  • 2
    If you don't want to create a global variable, you can use `.data()` to assign the interval id to the select element itself. Takes a bit more code, but I know some people don't like creating global variables. – Gavin Jul 17 '17 at 21:14
  • here an example of what @Gavin commented: https://stackoverflow.com/a/29417088/2617123 – epineda May 14 '20 at 05:12
  • I'd argue that using an HTML element to store application state has more pitfalls than using global state, but you can easily avoid global state by either bundling your modularized code with the likes of https://webpack.js.org or just by wrapping your code in a self-executing function: http://markdalgleish.com/2011/03/self-executing-anonymous-functions – glortho May 15 '20 at 17:26
7

I recommend you to use underscore.js then:

var newFunction=_.debounce(function (){ 
  alert('You function, after use stop scroll')
},1000); //Wait seconds after he stops

$('#select').change(newFunction);

Read more about underscore.debounce.

Aminadav Glickshtein
  • 23,232
  • 12
  • 77
  • 117