Rok*_*jan 36 javascript jquery
我想知道如何实现:在随机数量的时间后生成一个随机数.并重复使用它.
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 500"s)
}, rand);
Run Code Online (Sandbox Code Playgroud)
并反复做.
到目前为止,我能够生成一个随机间隔,但它会持续相同,直到刷新页面(生成不同的时间间隔).
谢谢
Akk*_*uma 85
这是一个非常干净,清晰的方法:
http://jsfiddle.net/Akkuma/9GyyA/
function doSomething() {}
(function loop() {
var rand = Math.round(Math.random() * (3000 - 500)) + 500;
setTimeout(function() {
doSomething();
loop();
}, rand);
}());
Run Code Online (Sandbox Code Playgroud)
编辑:
说明:循环仅存在于立即调用的函数上下文中,因此它可以递归调用自身.
这是一个可以清除的可重用版本。作为启用 IntelliSense的 NPM 包开源。
实用功能
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) },
};
};
Run Code Online (Sandbox Code Playgroud)
用法
const interval = setRandomInterval(() => console.log('Hello World!'), 1000, 5000);
// // Clear when needed.
// interval.clear();
Run Code Online (Sandbox Code Playgroud)
这样的东西应该工作 - setTimeout()改为使用,这样你每次都可以设置一个新的随机值:
function doSomething() {
alert("doing something");
}
function init() {
var myFunction = function() {
doSomething();
var rand = Math.round(Math.random() * (3000 - 500)) + 500; // generate new time (between 3sec and 500"s)
setTimeout(myFunction, rand);
}
myFunction();
}
$(function() {
init();
});
Run Code Online (Sandbox Code Playgroud)