Answer the question
In order to leave comments, you need to log in
How to correctly make a tick of 1 second?
Tell me how to make a server script tick so that it corresponds to 1 second of real time.
I understand that it needs to be included in 0ms. How to do it right? setInterval(moveLoop, 1000);
I don’t know how to explain it more precisely, so that it works every second, for example 01,02,03 ... 10
And not 01.5, 02.5, 03.5 .... 10.5
Answer the question
In order to leave comments, you need to log in
setTimeout(function(){
setInterval(moveLoop, 1000);
}, 1000-(+Date.now()%1000));
Output with the closest possible value to the current time, adjusted for the execution time of the handler function
function startTimer(cb) {
var timer = {running: true};
function interval() {
if (timer.running === false) return;
console.log('tick: ', (new Date()).toISOString());
cb();
setTimeout(interval, 1100 - (Date.now() + 100) % 1000);
}
setTimeout(interval, 1100 - (Date.now() + 100) % 1000);
return timer;
}
function stopTimer(timer) {
timer.running = false;
}
// test
function payload() {
var start = Date.now();
for (var i = 0; i < 10000000; i++); // нагрузка
var stop = Date.now();
console.log('payload:', stop - start)
}
var timer = startTimer(payload);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question