1

Beginning with node.js, I try to invoke a function after a random amount of time.

Why does this not work :

function main() {
    console.log('*** START ***');
}

function blink() {
    console.log('*** BLINK ***');
}

main();
var delay = Number(Math.random(1000, 10000));
setTimeout(blink, delay);

If I replace the random generated number with a static one, it works :

function main() {
    console.log('*** START ***');
}

function blink() {
    console.log('*** BLINK ***');
}

main();
setTimeout(blink, 3000);

Where did I go wrong ?

Chryor
  • 115
  • 2
  • 15

2 Answers2

2

Because Math.random() doesn't take arguments.

You want this:

var delay = 1000 + Math.random() * 9000;
robertklep
  • 198,204
  • 35
  • 394
  • 381
1

Value returned by Number(Math.random(1000, 10000)) is like 0.37.. or 0.39... which is too less for setTimeout, because setTimeout uses this value as milliseconds and thus the delay is too low or negligible.

This should work for you:

setTimeout(blink, delay*1000);
Viddesh
  • 441
  • 5
  • 18