我正在尝试模拟轮盘赌,每1/10秒显示一次随机数和背景色(黑色或红色)。下面的代码可以正常运行,但是我希望该函数仅运行特定的时间,例如5秒。我想我需要使用setTimeout(),但是我无法使其与下面的代码一起使用。
$('#spin').click(function(){
function spinWheel() {
var rouletteNum = Math.floor((Math.random() * 36) + 1);
$('#rouletteWheel').html(rouletteNum);
var color = ['red', 'black']
var i = [Math.floor(Math.random()*color.length)];
$('#rouletteWheel').css('background-color', color[i]);
}
setInterval(spinWheel, 100);
});
一种简单的解决方案是使用计数器
$('#spin').click(function () {
var counter = 0,
loopCount = 50 //10 times in a second * 5 seconds
;
function spinWheel() {
if (++counter >= loopCount) {
clearInterval(interval);
}
var rouletteNum = Math.floor((Math.random() * 36) + 1);
$('#rouletteWheel').html(rouletteNum);
var color = ['red', 'black']
var i = [Math.floor(Math.random() * color.length)];
$('#rouletteWheel').css('background-color', color[i]);
}
var interval = setInterval(spinWheel, 100);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句