Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
137
rated 0 times [  138] [ 1]  / answers: 1 / hits: 60357  / 13 Years ago, fri, august 5, 2011, 12:00:00

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.....
}

var rand = 300; // initial rand time

i = setinterval(function(){

doSomething();
rand = Math.round(Math.random()*(3000-500))+500; // generate new time (between 3sec and 500s)

}, rand);


And do it repeatedly.



So far I was able to generate a random interval, but it last the same until the page was refreshed (generating than a different time- interval).



Thanks


More From » jquery

 Answers
6

Here's a reusable version that can be cleared. Open-sourced as an NPM package with IntelliSense enabled.



Utility Function



const setRandomInterval = (intervalFunction, minDelay, maxDelay) => {
let timeout;

const runInterval = () => {
const timeoutFunction = () => {
intervalFunction();
runInterval();
};

const delay = Math.floor(Math.random() * (maxDelay - minDelay + 1)) + minDelay;

timeout = setTimeout(timeoutFunction, delay);
};

runInterval();

return {
clear() { clearTimeout(timeout) },
};
};


Usage



const interval = setRandomInterval(() => console.log('Hello World!'), 1000, 5000);

// // Clear when needed.
// interval.clear();

[#90788] Thursday, August 4, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alejandro

Total Points: 231
Total Questions: 102
Total Answers: 107

Location: Jordan
Member since Wed, Jun 17, 2020
4 Years ago
alejandro questions
Mon, Jul 18, 22, 00:00, 2 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
Thu, Sep 10, 20, 00:00, 4 Years ago
;