Antonio Cinaglia
Antonio Cinaglia

Reputation: 23

Reseting an JavaScript Interval with different value?

I have a small issue I can't seem to fix. I have a simple JavaScript code where I want to create a Interval that goes for a random amount of seconds, then after it finishes it should start over again and go for another random amount of seconds.

My code looks like this

var selectedtimes = [3000, 5000, 15000, 10000]
var randtimes = selectedtimes[Math.floor(Math.random() * selectedtimes.length)];

var sti = setInterval(function() {
  console.log("now")
}, randtimes);

function restartsti() {
  var restartinterval = setInterval(restartsti, selectedtimes[Math.floor(Math.random() * selectedtimes.length)]);
}

I tried to create a second function that would restart the interval but at the moment the interval takes only one random number and only uses that specific number as the duration.

To simplify my Node.js console should show "now" every randtimes seconds

Any solution to this?

I'm grateful for any help

Upvotes: 1

Views: 65

Answers (2)

Luke Horvat
Luke Horvat

Reputation: 337

setInterval is appropriate to use when the delay is intended to be consistent.

Since your delay is meant to be different each time, it's probably better to use setTimeout here:

var times = [3000, 5000, 10000, 15000];

function start() {    
  console.log("now");
  var randTime = times[Math.floor(Math.random() * times.length)];
  setTimeout(start, randTime);
}

start();

Upvotes: 5

Guillaume Georges
Guillaume Georges

Reputation: 4020

As Luke said, it's probably better to use setTimeout.

But if you want to keep using setInterval, you could stop the old one with clearInterval (providing the intervalID returned by the setInterval function) and start a new one :

var selectedtimes = [3000, 5000, 15000, 10000]

var randtimes = selectedtimes[Math.floor(Math.random() * selectedtimes.length)];


var sti = setInterval(function () {
    console.log("now")
    }, randtimes);

function restartsti() {
    clearInterval(sti);

    sti = setInterval(function() {
        console.log("now");
        restartsti()
    }, selectedtimes[Math.floor(Math.random() * selectedtimes.length)]);
}

Upvotes: 1

Related Questions