English 中文(简体)
jQuery/JavaScript:中断事件?
原标题:jQuery/JavaScript: interrupt event?

这是一个非常基本的JavaScript问题,可能重复,但我不知道答案!

我的代码如下:

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

我的问题是,如果调用.change()事件,userlist_change函数就会启动,而且速度相对较慢。如果用户再次更改列表(例如通过键入),我的代码将等待userlist_change完成,然后使用新值重新启动它。

这在UI中看起来很奇怪,因为任何事情都可能需要几秒钟的时间才能更改客户端——有时第一次调用的结果只有在用户已经进行了第二次调用之后才会出现。

当触发.change()或`keypress()事件时,是否有任何方法可以中断任何现有的userlist_change进程?

[EDIT]理想的做法是用这个名称命令简单地杀死任何正在运行的函数——这可能吗?还是我真的要摆弄计时器?!

问题回答

您可以将最后一次请求时间存储在一个全局变量中,并在每个ajax请求中存储一个请求时间,这样,当您刚刚显示第一次请求的结果时,如果全局最后一次申请时间大于请求、请求时间,则应显示,否则不显示。例如:

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

您应该使用事件的限制。使用RX for JavaScript很容易做到这一点,但库相当复杂。您可以尝试使用计时器筛选值。

这里有一个有用的节流插件:http://benalman.com/projects/jquery-throttle-debounce-plugin/





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签