的Javascript:触发这种情况发生在几秒钟的事件,但能如果另一个事件发生,取消该事件?事件、这种情况、几秒钟、但能

2023-09-10 20:15:41 作者:毒药°

免责声明:我是什么,但一个JavaScript专家,所以我甚至不知道如果我正确地处理这个...

Disclaimer: I am anything but a Javascript expert, so I'm not even sure if I'm approaching this correctly...

我希望能够触发在Javascript中的事件,但可以当另一个事件时取消该事件。那么,是什么,我希望实现的是:

I want to be able to trigger an event in Javascript, but be able to cancel that event if another event occurs. So, what I'm looking to accomplish is:

在用户开始输入文本框。 当文本​​框内容发生变化,触发一个事件,使一个AJAX调用 但是,如果用户不断输入,取消该事件,因为我不想做查询,直到后,他们完成打字 User begins typing in a text box. When textbox contents change, trigger an event that makes an AJAX call BUT, if the user keeps on typing, cancel that event, because I don't want to do the query until after they are finished typing

即。如果用户输入foobar的中,我不想做的AJAX搜索,直到他们完成打字。没有任何理由让我做的事:

i.e. If the user is typing "foobar" in, I don't want to do the AJAX search until they're done typing. There is no reason for me to do:

AJAX(F) 接着 AJAX(FO) 接着 AJAX(富) 接着 AJAX(foob) ......

AJAX("f") and then AJAX("fo") and then AJAX("foo") and then AJAX("foob") ...

当我刚做了一个呼叫,当他们完成打字 AJAX(FOOBAR)

when I could have just done a single call when they were done typing AJAX("foobar")

...我会做任何意义吗?还是有更好的方法来处理这​​个?

... am I making any sense? Or is there a better way to approach this?

呵呵,然后起脚!我想避免的JQuery /样机,并为此与只是直接的JavaScript ... yeck

Oh, and then the kicker: I'd like to avoid JQuery/Prototype, and do this with just straight javascript... yeck!

推荐答案

您想要做的关键preSS是什么

What you want to do on keypress is

if(myTimeout)
   window.clearTimeout(myTimeout);

var myTimeout = window.setTimeout(function() {
   alert('one second has passed without any keypress');
}, 1000);