我正在创建一个聊天脚本,当有人打字时,我需要每三秒运行一次一些代码。我可以使用 setInterval 轻松地每三秒运行一次代码,但是将 setInterval 放入我的按键事件中会导致它从每次按键的开头开始,因此它永远不会运行,直到他们停止键入。另一个问题是当他们停止打字时停止它。有什么想法吗?
$("#message").keypress(function(event){
// Do stuff here every keypress
// Every three seconds, while someone is typing do this:
ws.send(JSON.stringify({"type": "typing", "from": {"id": client.self.id, "hash": client.self.hash}, "to": {"id": client.partner.id, "hash": client.partner.hash}}));
});
最佳答案
当发生以下两种情况之一时,您就会知道有人已经停止打字:
- 字段失去焦点(因为用户选择了选项卡/单击了退出),这当然很容易使用
blur
事件处理程序进行测试,或者 - 在 x 毫秒内没有发生任何按键事件,其中 x 是相当主观的,随着打字速度的不同而变化,但可能是 500 毫秒左右。您可以在 key 处理程序中使用
setTimeout()
和clearTimeout()
对此进行测试。
所以,也许这样的东西适合你:
var timeoutId,
intervalId;
function stopMyInterval() {
clearInterval(intervalId);
intervalId = null;
}
$("#message").keypress(function(event){
clearTimeout(timeoutId); // user is still typing, so cancel previous timeout
if (!intervalId) {
intervalId= setInterval(function() {
ws.send(JSON.stringify({"type": "typing", "from": {"id": client.self.id, "hash": client.self.hash}, "to": {"id": client.partner.id, "hash": client.partner.hash}}));
}, 3000);
}
timeoutId= setTimeout(stopMyInterval, 500);
// try some different values here -----^^^ until it feels natural.
}).blur(stopMyInterval);
请注意,在调用 clearInterval()
/clearTimeout()
之前,您实际上并不需要测试是否已设置间隔/超时(如果您调用,则两者都不是函数对象)向其传递无效值)。
关于javascript - 调用事件时每隔几秒运行一次代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20917428/