我正在实现一个带有自动建议值的文本框,它在按下每个键时从 mysql 数据库中获取值。因为我在数据库中有大量值,所以我的函数需要时间。此外,对函数的每次调用都是按顺序运行的
假设 我按下了一个键,它触发了一个事件并开始执行 func。 然后我按下 B 键,这再次触发了一个事件,但现在我希望在运行第二个函数之前先杀死 func
我怎样才能做到这一点?
在搜索时我发现线程可以用来实现这个。但我仍然无法通过线程实现。如果有人知道确切的过程吗?
最佳答案
这被用作一个很好的(在我看来)求职面试问题,Nathan Leclaire wrote about it on his blog .
相关摘录:
if we use window.setTimeout we can delay the call for 200 milliseconds. ... But that’s not going to help us in the case where the user is typing fast, or even just normal speed. So we need a way to interrupt the timeout if the user keeps typing.
...
So, I know that when you call
window.setTimeout
, you get back an ID that uniquely references the timeout. And you can use it to cancel the timeout if need be! So we should just store the timeout ID in the keypress function closure, and if the user triggers a keypress event again before the timeout function triggers, we’ll just cancel it and set a new one!
最后,他分享了一些代码示例,我想这可以帮助您优化您的功能!
$(document).ready(function() {
$('input').keypress(function() {
if (this.timeoutId)
window.clearTimeout(this.timeoutId);
this.timeoutId = window.setTimeout(function () {
$.ajax({
// do some stuff
});
}, 200);
});
});
关于python - 在按下的每个键上实现自动建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21940904/