Javascript 在随机区间内执行随机函数(JQUERY)
我想在随机时间间隔内做一个随机函数。 以下是代码:Javascript 在随机区间内执行随机函数(JQUERY),javascript,jquery,Javascript,Jquery,我想在随机时间间隔内做一个随机函数。 以下是代码: function numberOne() { $("#here").hmtl("numberOne"); } function numberTwo() { $("#here").hmtl("numberTWO"); } var randomfunction = [numberOne, numberTWO] var randomfuncti
function numberOne() {
$("#here").hmtl("numberOne");
}
function numberTwo() {
$("#here").hmtl("numberTWO");
}
var randomfunction = [numberOne, numberTWO]
var randomfunction = randomfunction[Math.floor(Math.random() * randomfunction.length)];
(function loop() {
var rand = Math.round(Math.random() * (1000 - 500)) + 500;
setTimeout(function() {
randomfunction();
loop();
}, rand);
}());
它不起作用。我不知道为什么。你能帮我解释一下所有的错误吗?谢谢 如果您正在检查控制台,您会发现它会引发以下错误: 未捕获引用错误:未定义numberTWO 因此,只要解决此问题,您的代码就能正常工作,请替换:
var randomfunction = [numberOne, numberTWO];
作者:
希望这有帮助。我看到一个错误的函数调用,hmtl而不是html 但我认为我们可以改变你的方法,把它提高到一个新的水平。你可以这样做
function numberOne() {
$("#here").html("numberOne");
}
function numberTwo() {
$("#here").html("numberTwo");
}
var randomFunctionsArray = [numberOne, numberTwo];
function loop() {
randomFunctionsArray[Math.floor(Math.random() * randomFunctionsArray.length)]();
setTimeout(function() {
var rand = Math.round(Math.random() * (1000 - 500)) + 500;
loop();
}, rand);
}
loop();
jQueryfunction${
功能一{
console.log'one';
}
功能二{
console.log'two';
}
var functions=[functionOne,functionTwo];
函数环{
var waitTime=Date.now%5000;
var executionIndex=Date.now%functions.length;
console.logexecutionIndex;
console.logwaitTime;
函数[执行索引];
setTimeoutloop,waitTime;
};
};
它不工作,因为在中甚至无法运行,运行但在某个点爆炸,运行但没有达到我的预期,或者…?我知道有。hmtl,但这仍然不起作用!:
function numberOne() {
$("#here").html("numberOne");
}
function numberTwo() {
$("#here").html("numberTwo");
}
var randomFunctionsArray = [numberOne, numberTwo];
function loop() {
randomFunctionsArray[Math.floor(Math.random() * randomFunctionsArray.length)]();
setTimeout(function() {
var rand = Math.round(Math.random() * (1000 - 500)) + 500;
loop();
}, rand);
}
loop();