AP257
AP257

Reputation: 93793

jQuery/JavaScript: interrupt event?

This is a really basic JavaScript question and probably duplicate, but I don't know the answer!

I have code as follows:

function userlist_change(myval, function_type) {
   // relatively slow code involving Ajax call  
   // based on Ajax results, change some client-side stuff
}
$("#subjectlist").change(function() { 
    userlist_change($("#subjectlist").val(), 'change');
}).change(); 
$("#subjectlist").keypress(function() { 
    userlist_change($("#subjectlist").val(), 'keypress');
}); 

I have the problem that if the .change() event is called, the userlist_change function kicks off, and it's relatively slow. If the user changes the list again (e.g. by typing), my code waits for userlist_change to complete before restarting it with the new value.

This looks quite odd in the UI, as it can take a few seconds for anything to change client-side - and sometimes the results of the first call only appear after the user has already made a second call.

Is there any way I can interrupt any existing userlist_change process when the .change() or `keypress() event is fired?

[EDIT] What would be ideal is a simple 'kill any running functions with this name' command - is this possible? Or do I really have to fiddle around with timers?!

Upvotes: 0

Views: 1009

Answers (2)

gor
gor

Reputation: 11658

You should use throttling of event. It is quite easily done with RX for JavaScript, but library is quite complicated. You can try filter value with timer.

Here is useful plugin for throttling: http://benalman.com/projects/jquery-throttle-debounce-plugin/

Upvotes: 0

Adeel
Adeel

Reputation: 19228

you can store last request time in a global variable, and store a request time in each ajax request, so that when you are just showing the result of first request, if the global last request time is greater than request, request time, you should show, other wise not. For example:

var lastRequestTime;

function userlist_change(myval, function_type,requestTime) {

   // relatively slow code involving Ajax call  
   // based on Ajax results, change some client-side stuff

if(lastRequestTime <= requestTime){
 //show
}
}
$("#subjectlist").change(function() { 
    lastRequestTime = new Date();
    userlist_change($("#subjectlist").val(), 'change',lastRequestTime );
}).change(); 
$("#subjectlist").keypress(function() { 
    lastRequestTime = new Date(); 
    userlist_change($("#subjectlist").val(), 'keypress',lastRequestTime );
}); 

Upvotes: 1

Related Questions