The "writes..." notification gets bugged after a while

31 Views Asked by At

I have a chat with the code below, when I type something in the chat, the message "I'm typing..." appears, but for some reason, after typing for a while, the "I'm typing..." notification seems to have entered a bug. I can't understand why this is?

After a while, it starts to close and open without a time interval as I write.

Node.JS;

const express = require('express');
const socket = require('socket.io');

const app = express();
const server = app.listen(3000)

app.use(express.static('public'))

const io = socket(server);

io.on('connection', (socket) => {
console.log(socket.id)

socket.on('chat', data => {
    io.sockets.emit('chat', data)
})
socket.on('typing', data => {
    socket.broadcast.emit('typing', data)
})
})

JavaScript;

const socket = io.connect('http://localhost:3000');

const sender = document.getElementById('sender');
const message = document.getElementById('message');
const submitBtn = document.getElementById('submitBtn');
const output = document.getElementById('output');
const feedback = document.getElementById('feedback');

submitBtn.addEventListener('click', () => {
    if (sender.value != '' && message.value != '') {
        socket.emit('chat', {
            message: message.value,
            sender: sender.value,
            });
        sender.disabled = true;
    }
})

socket.on('chat', data => {
    feedback.innerHTML = ''
    output.innerHTML += '<p><strong>' + data.sender + ' : </strong>' + data.message + '</p>'
    message.value = '';
})

message.addEventListener('keypress', () => {
        socket.emit('typing', sender.value)
})

socket.on('typing', data => {
    feedback.innerHTML = '<p>' + data + ' typing...</p>';

    setTimeout(() => {
    feedback.innerHTML = ''
}, 5000);
})
1

There are 1 best solutions below

2
Whale Shark On

I think that everytime you type in chat you're creating a new timeout that isn't cleared the next time you type in chat, so you should get a handle on it using a variable and clear it if it's not undefined. This is for the last few lines of code in your JS file:

var timeoutHandle;
socket.on('typing', data => {
    if (timeoutHandle !== undefined) {
         clearTimeout(timeoutHandle);
     }
    feedback.innerHTML = '<p>' + data + ' typing...</p>';

    timeoutHandle = setTimeout(() => {
    feedback.innerHTML = ''
    }, 5000);
})