I
I
Inter Carpenter2016-02-02 16:38:17
JavaScript
Inter Carpenter, 2016-02-02 16:38:17

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

2 answer(s)
D
Dasha Tsiklauri, 2016-02-02
@dasha_programmist

setTimeout(function(){
   setInterval(moveLoop, 1000);
}, 1000-(+Date.now()%1000));

A
Alexey, 2016-02-02
@alexeyproject

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);

Pay attention to 1100 - (Date.now() + 100) % 1000
This shifts from the zero position so that there are more than 100ms between timer calls.
This number can be adjusted. As you know, there cannot be less than 4ms between calls, therefore (given a small margin) I do not recommend setting it to less than 10ms. With this value, the maximum execution time of the handler, in order to avoid skipping the timer, will be 989ms, if the handler runs longer, then the next call will be skipped.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question