題我正在使用為聊天室setTimeout()實現“用戶正在鍵入”消息。超時存儲在句柄中,以便可以在連續按鍵時清除超時并重置,以便超時真正代表用戶完成輸入的時間。但是,假設有一個聊天室,里面有聊天者 A、B 和 C。如果 A 開始打字,那么 B 開始打字,A 的超時被清除并且永遠不會消失。那么,有沒有一種方法可以動態創建超時句柄,以便無論聊天室中有多少用戶或當前正在打字,我都只能清除相應的句柄?代碼索引.jsio.on('connection', function(socket){ socket.on('csTyping', function(user){ socket.broadcast.emit('scTyping', user); });});聊天.jsvar typingLock = false;var tMsgTimeout = 1 * 1000;var tLockTimeoutHandle = window.setTimeout(() => { typingLock = false;}, tMsgTimeout);window.clearTimeout(tLockTimeoutHandle);var tMsgTimeoutHandle = window.setTimeout(() => { removeTypingMsg(0);}, tMsgTimeout);window.clearTimeout(tMsgTimeoutHandle);message.addEventListener('keypress', function(){ if (!typingLock) { socket.emit('csTyping', clientUsername); typingLock = true; window.clearTimeout(tLockTimeoutHandle); tLockTimeoutHandle = window.setTimeout(() => { typingLock = false; }, tMsgTimeout); }});socket.on('scTyping', function(user){ feedback.innerHTML += "<p id='typing" + user + "'><em>" + user + " is typing a message...</em></p>"; window.clearTimeout(tMsgTimeoutHandle); tMsgTimeoutHandle = window.setTimeout(() => { removeTypingMsg('typing' + user); }, tMsgTimeout);});
如何在 JavaScript 中創建動態超時句柄?
qq_遁去的一_1
2021-11-25 19:04:33