简体   繁体   English

setTimeout似乎越来越短

[英]setTimeout seems to be getting shorter

I am writing a chatbot application and wanted to catch multiple user inputs by blurring out of the input field and focussing back in after 3 seconds (when the bot responded). 我正在编写一个聊天机器人应用程序,希望通过模糊输入字段并在3秒钟后(机器人响应时)重新集中注意力来捕获多个用户输入。

I used setTimeout for this and it works the first time but it seems to get shorter after calling the function multiple times. 我为此使用了setTimeout,它第一次起作用,但是多次调用该函数后,它似乎变短了。

The code I used is in a React chat widget and looks like this: 我使用的代码在React聊天小部件中,如下所示:

handleKeyPress = (e: KeyboardEvent) => {
    if (e.keyCode === 13 && this.input.value.replace(/\s/g, "")) {
        this.input.blur();
        this.say(this.input.value);
        // Reset input value
        this.input.value = "";
        this.refocus(document.getElementById('userText'));
    }
};

refocus = (element: HTMLElement) => {
    var time = setTimeout(function() {
        element.focus();
    }, 3000);
};

In this code I use a setTimeout after sending the message to the backend bot application so that the bot has some time to answer. 在这段代码中,我在将消息发送到后端机器人应用程序之后使用了setTimeout,以便机器人有一些时间来回答。

I can't figure out why this is not working and could really use some suggestions... 我不知道为什么这不起作用,真的可以使用一些建议...

I found a fix for my issue. 我找到了解决我的问题的方法。 It appears that the problem had something to do with the focus() / blur() methods. 看来问题与focus() / blur()方法有关。 I used a disable = true and disable = false and focus() after the 3 second delay and now the delay is always 3 seconds. 我在3秒延迟后使用了disable = truedisable = falsefocus() ,现在延迟始终为3秒。

Code now looks like this: 现在的代码如下所示:

handleKeyPress = (e: KeyboardEvent) => {
    if (e.keyCode === 13 && this.input.value.replace(/\s/g, "")) {
        this.input.disabled = true;
        this.say(this.input.value);
        // Reset input value
        this.input.value = "";
        this.enable((document.getElementById('userText') as HTMLInputElement));
    }
};

enable = (element: HTMLInputElement) => {
    setTimeout(function() {
        element.disabled = false;
        element.focus();
    }, 3000);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM