我尝试过Math.random,但是它显示它是未定义的。
function startBlinking() {
setInterval(function() {
blink();
}, 8000);
}
function blink() {
goggleY = goggleY - 25;
setTimeout(function() {
if (goggleY > goggleY - 25) {
goggleY = goggleY + 25
}
}, 150);
}有没有一种方法可以在设定的数值内随机调用函数?(例如: random(1,10))?如有任何帮助,我们将不胜感激:)
发布于 2020-10-20 23:24:16
摘自setTimeout() - in for loop with random delay
setTimeout(function () {
console.log(i);
}, Math.floor(Math.random() * 1000)就是你要找的东西。所以在你的情况下
//Function to generate random int from min to max inclusive on both ends
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function blink() {
goggleY = goggleY - 25;
setTimeout(function() {
if (goggleY > goggleY - 24) {
goggleY = goggleY + 25
}
}, getRandomInt(1,10));
}
blink();对你来说,对setTimeout进行随机化的重要部分是逗号后面的最后一位。
setTimeout(function(){ alert("Hello"); }, <'the part where we set how long to wait in milliseconds'>);祝你好运,祝你黑客生涯愉快。
发布于 2020-10-20 22:24:32
function blink() {
goggleY = goggleY - 25;
setTimeout(function Math.random() {
if (goggleY > goggleY - 24) {
goggleY = goggleY + 25
}
}, 150);
}
startBlinking();
Heres the code with Math.randomhttps://stackoverflow.com/questions/64447110
复制相似问题