setTimeout not working with random delay

为君一笑 提交于 2021-02-10 16:58:08

问题


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 ?


回答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);



回答2:


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

You want this:

var delay = 1000 + Math.random() * 9000;


来源:https://stackoverflow.com/questions/31986016/settimeout-not-working-with-random-delay

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!