运行一段特定时间的function

我正在尝试模拟轮盘赌轮,每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); }); 

为此,我们可以使用Date对象。 这得到自1970年左右以来的毫秒数。所以我们用Date.now()定义了一个开始时间,然后调用它start然后5秒后将是: end = start + 5000 。 然后我们将在每次调用函数时更新start ,一旦start end我们需要以clear interval结束我们的clear interval

 var start = Date.now(); // The current date (in miliseconds) var end = start + 5000; // 5 seconds afterwords function spinWheel() { start = Date.now(); // Get the date currently /* Your code here */ if(start > end) clearInterval(timer); // If we are 5 seconds later clear interval } var timer = setInterval(spinWheel, 100); 

示例小提琴 – 注意它在5秒后停止

注意:在这种情况下你也可以使用计数器,但是如果你希望你的时间在5秒之后直接准确,那么不建议这样做,因为setInterval()可能会漂移。 但大部分时间它都会非常接近。 日期会更准确。 如果你只是寻找“非常接近或在5秒钟”,做一个计数器将工作正常。

嘿,你可以清除你的间隔,例如10次。

  $('#spin').click(function(){ counter = 0; howManyTimes = 10; var interval = setInterval(function () { counter++ if(counter === howManyTimes) { clearInterval(interval); alert('game over'); } else { 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]); } },100); interval(); }); 

工作示例jsfiddle clear interval