在特定时间段内运行功能 [英] Run a function for a specific amount of time

查看:98
本文介绍了在特定时间段内运行功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试模拟轮盘赌,每1/10秒显示一次随机数和背景色(黑色或红色).下面的代码可以正常运行,但是我希望该函数仅运行特定的时间,例如5秒.我想我需要使用setTimeout(),但无法使其与下面的代码一起使用.

I'm trying to simulate a roulette wheel, displaying random numbers and background color (black or red) every 1/10 second. The code below is working as desired, however I would like the function to run only for a specific amount of time, like 5 seconds. I think I need to use setTimeout(), but I can't get it to work with the code below.

$('#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);
});

推荐答案

一种简单的解决方案是使用计数器

One easy solution is to use a counter

$('#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);
});

这篇关于在特定时间段内运行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆