我有一个带有函数警报的设置间隔:
setInterval(function(){
alert('oo');
}, 5000);但是,我想改变我的(5000)间隔,每次运行警报()-我想让它随机选择5-10秒。我该怎么做呢?
发布于 2016-01-07 13:56:53
您应该使用setTimeout来设置执行函数的间隔。
function myFunction() {
var min = 5,
max = 10;
var rand = Math.floor(Math.random() * (max - min + 1) + min); //Generate Random number between 5 - 10
console.log('Wait for ' + rand + ' seconds');
setTimeout(myFunction, rand * 1000);
}
myFunction()
发布于 2016-01-07 13:52:56
你可以这样做:
function myFunction() {
alert('oo');
setTimeout(myFunction, Math.random() * 5000)
}
myFunction()
发布于 2020-09-27 10:34:31
您可以使用两个方法来完成这个任务,第一个是setTimeout方法,第二个方法是requestAnimationFrame方法。
以下是这两方面的完整例子。
带setTimeout的随机区间
function randomInterval(callback, min, max) {
let timeout;
const randomNum = (max, min = 0) => Math.random() * (max - min) + min;
const stop = () => clearTimeout(timeout)
const tick = () => {
let time = randomNum(min, max);
stop();
timeout = setTimeout(() => {
tick();
callback && typeof callback === "function" && callback(stop);
}, time)
}
tick();
}使用requestAnimationFrame的随机间隔
function randomInterval(callback, min, max) {
const randomNum = (max, min = 0) => Math.random() * (max - min) + min;
let targetTime = randomNum(min, max);
let lastInvoke = performance.now();
const stop = () => targetTime = null
const tick = () => {
if (!targetTime) return;
if (performance.now() - lastInvoke > targetTime) {
lastInvoke = performance.now();
targetTime = randomNum(min, max);
callback && typeof callback === "function" && callback(stop);
}
requestAnimationFrame(tick)
}
tick();
}下面是一个如何将其称为
randomInterval((stop) => {
// do what you want...
if (stopCondition) {
stop();
}
}, 1000, 3000)https://stackoverflow.com/questions/34656758
复制相似问题