Skip to content Skip to sidebar Skip to footer

Run A Function For A Specific Amount Of Time

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

Solution 1:

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);
});

Solution 2:

To do this we can use the Date object. Which gets the number of milliseconds since around 1970. So we defined a starting time with Date.now() and call it start then 5 seconds later would be: end = start + 5000. Then we will update start each time we call our function, once start goes past end we need to end our interval with 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);

Example fiddle - Notice it stops after 5 seconds

Notice: You can use a counter in this case as well, but if you want your time to be directly after 5 seconds and be accurate, it's not recommend, as it's possible for setInterval() to drift. But it will be quite close most of the time. Date will be more accurate. If you are just looking for "very close to or at 5 seconds", doing a counter will work fine.


Solution 3:

Hey you can clear your interval after for example 10 times.

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

working example jsfiddle clear interval


Post a Comment for "Run A Function For A Specific Amount Of Time"