user13107258
user13107258

Reputation: 59

Timer run every 5 minutes React JS (javascript)

I want to set timer every 5th minute. Example: timer countdown 5 minutes only at time 00:00 , 00:05 , 00:10 , 00:15 etc. in 00:17 timer should countdown 3 minutes

how setTimeout and setInterval with that provision? I would like to do it programmatically, in React JS using javascript, anyone can help me?

Upvotes: 0

Views: 1862

Answers (1)

RobG
RobG

Reputation: 147363

When you want a function to run at a specific clock time, like every full minute, it's usually best to use setTimeout with sequential calls. That way you can work out the time to the next whole "tick" and set the timeout for that interval. This stops small lags caused by the system being busy accumulating, making the timing drift.

Using setInterval lags accumulate so the timing slowly drifts. The first run needs setTimeout anyway to start it at the right time (e.g. next full tick).

Here's a simple example to run a function on whatever tick you want, specified in milliseconds. The example is every 30 second tick but if you want 5 minutes just call it with 3e5 (i.e. 5 * 60 * 1000 = 300,000 which is the number of milliseconds in 5 minutes). Then it will run at the next full tick and every tick after that until cancelled.

setTimeout also returns an identifier (timer id, not used in the example) that you can use to stop it if necessary.

/**
 * Run a function on every tick at specified interval. First
 * call of fn is on next tick. May be a few ms late depending
 * on system load when fn due to run.
 *
 * @param {Function} fn - function to call
 * @param {number} tick - clock tick to run function on in milliseconds
 *                        e.g. 30 secs = 3e4, 1 min = 6e4, 5 min = 3e5
 */
function onEveryTick(fn, tick) {
  // Time to next tick
  let getTick = () => tick - (Date.now() % tick);
  // Currie function to sequentially call itself
  let f = () => {
    fn();
    setTimeout(f, getTick());
  }
  // First call after required lag
  setTimeout(f, getTick());
}

// Call on 30 second tick
onEveryTick(() => console.log('Tick ' + new Date().toString()), 3e4);

Upvotes: 1

Related Questions