1

Disclaimer : I'm not super proficient in Javascript and there's this small JS code part in my .net program.

I have 2 dropdown lists, ReportList and YearList. The first one's selected value dynamically populates the second dropdown list using AJAX. The problem is, each time a ReportList is selected it makes a query to a database. There can be at least 200 entries in ReportList and when a user uses the mousewheel on the dropdownlist, the application, as is, makes hundreds of query in a short amount of time and crashes the database. So far I have this

             $('#ReportList').change(function () {
             setTimeout(function () { PopulateYearsDropdownList() }, 2000);
         });

I've played with stopPropagation() and it didn't work. I can't test it very efficiently since even the test DB is hosted and maintained by someone else.

I'd like to be able to scroll through without prompting as much queries as the amount of reports that have gone through. I was thinking of adding a small delay, with each function ".change" cancelling the last function call.

I think this wasn't really thought through from the beginning, but I want to fix this in the small amount of time I have.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Mortar9
  • 15
  • 3

3 Answers3

4

I'd suggest assigning setTimeout to a variable (with proper scope accessibility) and using clearTimeout to stop the timeout.

To read more about setTimeout and clearTimeout.

An example would look like:

var myTimeout;
$('#ReportList').change(function () {
    if (myTimeout) clearTimeout(myTimeout);
    myTimeout = setTimeout(function () { PopulateYearsDropdownList() }, 2000);
});
Mr. Meeseeks
  • 1,841
  • 2
  • 21
  • 37
  • 1
    This is exactly what needs to be done, only truly run the code in the handler if it's been a couple seconds since the last time the handler was called, that way if it's called a zillion times it just waits patiently until the user settles down and then makes 1 call at the end :) – Jimbo Jonny Jan 27 '16 at 21:08
  • @Mr-Meeseeks That's exactly what I've been looking for. Thanks! – Mortar9 Jan 29 '16 at 14:15
0

You should either save the responses to the memory or use $.ajax's caching abilities. The latter needs that your server sends the response with proper caching headers

Gavriel
  • 18,880
  • 12
  • 68
  • 105
0

Not 100% sure what you are trying to do, but you can set your timeout to a variable, and then at another point in time clear the timeout.

var myTimeout = setTimeout(PopulateYearsDropdownList(), 2000);

//...some more code

clearTimeout(myTimeout); //cancels the original setTimeout

You can also use .abort() to cancel your AJAX request How to cancel/abort jQuery AJAX request?

Community
  • 1
  • 1
Adjit
  • 10,134
  • 12
  • 53
  • 98