python - 在按下的每个键上实现自动建议

标签 python multithreading algorithm wxpython multiprocessing

我正在实现一个带有自动建议值的文本框,它在按下每个键时从 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/

相关文章:

python - 使用相同的DAGS创建新环境时,缺少FERNET_KEY配置

python - 如何在 python 包中包含 .pyx 文件

给定特定条件的排列的Python实现

python - 在 EC2 上运行 mapreduce 作业时如何获取文件名?

python - reshape Keras 张量

c++ - 对象被移动到另一个线程后不能简单地删除它吗?

python - input() 函数阻止新的多处理进程在通过 PyCharm 运行时启动

java - HashMap 中唯一键的线程安全性

c++ - 给定一个 N 个数的数组,求出范围为 R 的所有长度的序列的个数?

algorithm - 如何检查是否可以在字典中找到所有子字符串