gpt4 book ai didi

javascript - 如何在用户发送消息时停止 'is typing' 功能

转载 作者:搜寻专家 更新时间:2023-11-01 00:29:20 24 4
gpt4 key购买 nike

当用户按下回车键时,我的“用户正在输入”功能不会删除“正在输入”。因此,即使用户发送了消息,“正在输入”仍会显示,直到计时器用完。

有什么想法吗?

这是我的代码:

客户端

// Detect typing

function timeoutFunction() {
typing = false;
socket.emit("typing", false);
socket.emit("notTyping", true)
}

$("#msg").keypress(function(e){
if (e.which !== 13) {
if (typing === false && $("#msg").is(":focus")) {
typing = true;
socket.emit("typing", true);
} else {
clearTimeout(timeout);
timeout = setTimeout(timeoutFunction, 1500);
}
}
else if(e.which == 13 && $("#msg").val() !== "") {
$("#"+data.person+"").remove();
}
});

socket.on("isTyping", function(data) {
if (data.isTyping) {
if ($("#"+data.person+"").length === 0) {
socket.emit("checkTypingFunction");
$("#chat").append("<div id='"+ data.person +"'><span class='grey'>" + data.person + " is typing...</div>");
timeout = setTimeout(timeoutFunction, 1500);
}
} else {
$("#"+data.person+"").remove();
}
});

服务器端:

client.on("typing", function(data) {  
if (typeof people[client.id] !== "undefined")
socket.sockets.in(client.room).emit("isTyping", {isTyping: data, person: people[client.id].name});
client.broadcast.to(client.room).emit("isTyping", {isTyping: data, person: people[client.id].name});
console.log("Someone is typing");
});

最佳答案

您只是错过了用户按下 Enter 键时的大小写。您需要添加到您的 if 语句中。

$("#msg").keypress(function (e) {
if (e.which !== 13) {
typing = true; // we know the user is typing because they have pressed a key but not 'Enter'
socket.emit("typing", true);
clearTimeout(timeout);
timeout = setTimeout(timeoutFunction, 1500);
} else {
clearTimeout(timeout); // no need to fire the timeoutFunction twice (as we do it on the next line)
timeoutFunction(); // probably needs a better name but this will immediately send the necessary `socket.emit('typing', false)` when the enter key is pressed
}
});

关于javascript - 如何在用户发送消息时停止 'is typing' 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43541284/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com