Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery change with delay [duplicate]

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?

like image 696
GoldenNewby Avatar asked Feb 24 '12 03:02

GoldenNewby


2 Answers

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);
});
like image 131
glortho Avatar answered Oct 14 '22 14:10

glortho


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.

like image 25
Aminadav Glickshtein Avatar answered Oct 14 '22 15:10

Aminadav Glickshtein