Suttero
Suttero

Reputation: 91

How to generate new delay for setInterval every call?

Hello so i am wonering how i can archive delays in setInterval? Lets say i have something like this:

function delay(min, max) {
   const d = Math.floor((Math.random() * (max - min)) + min);
   return d;
}


setInterval(function() {
  console.log("Hello");
}, delay(1000, 2000));

The problem here is, that it console log, all the time with generated delay. And i want to generate new delay every console.log. Is it possible?

Upvotes: 1

Views: 39

Answers (1)

Sebastian Speitel
Sebastian Speitel

Reputation: 7346

You could use setTimeout and call it recursivly:

function delay(min, max) {
  const d = Math.floor((Math.random() * (max - min)) + min);
  return d;
}

function func() {
  console.log("Hello");
  setTimeout(func, delay(1000, 2000));
}

setTimeout(func, delay(1000, 2000));

A more general way would be your own interval generator:

function setVariableInterval(f, d) {

  function timeoutFunc() {
    f();
    setTimeout(timeoutFunc, d());
  }

  setTimeout(timeoutFunc, d());
}

//You would call it like:

setVariableInterval(func, delay.bind(null, 1000, 2000));

Upvotes: 3

Related Questions