Randomize setInterval ( How to rewrite same random after random interval)

后端 未结 5 2097
既然无缘
既然无缘 2020-11-29 22:18

I\'d like to know how to achieve: generate a random number after a random number of time. And reuse it.

function doSomething(){
     // ... do something.....         


        
5条回答
  •  一向
    一向 (楼主)
    2020-11-29 22:44

    Just throwing my hat in the ring

        var keepLooping = true;
        (function ontimeout(){
            if(keepLooping){
                doTheAction();
                setTimeout(ontimeout, Math.random() * 100);
            }
        })();
    

    depends if you want to put doTheAction() inside the setTimeout callback or not. I think it's fine to put it before/outside. If you want the initial delay, then put it inside, if not, put it outside for simplicity.

提交回复
热议问题