C
C
Cyril2020-10-07 11:38:49
JavaScript
Cyril, 2020-10-07 11:38:49

How to make timeouts for different users in Node JS?

I am making a telegram bot on Node, the essence of which is to create timers for users. The user can stop the timer at any time. How to make it so it can clear its timer?

My solution as a beginner developer. I created an array into which, when creating a timer, I add the {user_id, timeout} object. And when the user clicks on the stop, I do a clearTimeout for the desired object and then remove the object itself from the array.

function clearUserTimeout(user_id) {
    const indexOfTimeout = timeouts.findIndex(item => item.user_id === user_id)
    if (indexOfTimeout !== -1) {
        clearTimeout(timeouts[indexOfTimeout].timeout)
        timeouts.splice(indexOfTimeout, 1)
    }
}

How to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bqio, 2020-10-07
@bqio

I would store in the object not timer objects, but only the time in UNIX, at which time the user should stop the timer and make 1 general timer that runs through the objects every second (1.5-2) and checks the time specified there, compares it with the current one and if it is less than the current one, it sends a message to the user and ends its timer by changing some bool variable, or simply specifying the time as null.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question