I want to execute a script with a random interval between 11 to 13 minutes. I tried this code, but the script is execute in much less than 11 minutes. Is my calculation wrong?
setInterval(function() {
// code to be executed
const script = spawn('node', ['index.js']);
}, 1000 * 60 * Math.floor(Math.random() * 3) 11); // 1000 milliseconds * 60 seconds * random number of minutes between 11 and 13
CodePudding user response:
First thing, you are missing parenthesis.
It should be 1000 * 60 * (Math.floor(Math.random() * 3) 11)
instead of 1000 * 60 * Math.floor(Math.random() * 3) 11)
Secondly, Math.floor(Math.random() * 3)
can only take 3 possible values (0, 1 or 2), so your script will run either every 11, 12 or 13 minutes.
If you want more possible values between 11 and 13 minutes, you can compute the time interval this way:
Math.floor(1000 * 60 * (Math.random() * 3 11))
to have many possible values between 11 and 13 minutes.
This will do the job:
setInterval(function() {
// code to be executed
const script = spawn('node', ['index.js']);
}, Math.floor(1000 * 60 * (Math.random() * 3 11)); // 1000 milliseconds * 60 seconds * random number of minutes between 11 and 13