S
S
sferos2016-12-24 21:22:54
JavaScript
sferos, 2016-12-24 21:22:54

Who can help with timers in JS?

I have been sitting on such a problem for a long time, there is a server code, it contains a function that should be launched when the client calls it via sockets.

socket.on("one", function(result){
if(result===...){
foo();
}
});
function foo(){
//какой то код
}

But the fact is that the function needs to be launched after 30 seconds (if the client does not respond before that). Tried doing it like this:
socket.on("one", function(result){
if(result===...){
foo();
}
});
var interval;
function foo(){
clearInterval(interval);
//какой-то код, запуск других функций и т.д.
interval=setInterval(function(){foo();}, 30000);
}

But for me, declaring a global variable in server code is not good. In addition, requests from the client come at different times (after 5, 10, 15 seconds) and the acceleration of the interval still occurs. What can be done to fix this problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly, 2016-12-24
@vitali1995

Let's start with the fact that the variable is not global - in the server code it will only be available at the module level, so this is a normal practice called a closure (the alternative is to use classes). Requests in this form of recording will come at different times and you will have to put up with it - asynchronous node.js calls the timer callback only after the previous queue of callbacks in the event loop has been processed. If precise intervals are needed, a separate thread of the process must be forked, in which case it is good practice to move this timer to a separate service so as not to have a common memory area with the main part of the application (see the dangers of multi-threaded programming).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question