开发者

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 si开发者_Go百科mple 'kill any running functions with this name' command - is this possible? Or do I really have to fiddle around with timers?!


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 );
}); 


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜