Search code examples
javascriptfunctionperiod

How to run a javascript function X seconds?


I am using setInterval to run a Javascript function that generates a new, random integer in a div. the timer starts when I click on the div. I am having problems with stopping it form generating new numbers after five seconds.

Using setTimeout, I hide the div after 5 seconds; that stops random numbers, but I lose the div.

How can I efficiently stop the generating of numbers in the div, and not hide it?

HTML:

<div id="div" onmousedown='F();'>Click here</div>

JS:

function F(){
    var div = document.getElementById("div");

    setInterval(function(){                 
        var number = Math.floor(Math.random()*28)   ;           
        div.innerHTML = number;
    }, 1000);


    setTimeout(function(){                  
        div.style.display = 'none';
    },5000);
};

Solution

  • Just use a counter to keep track of the number of times the interval has ticked and then use clearInterval to stop it:

    var count = 0;
    var intervalID = setInterval(function() {
        // generate your random number
        count++;
        if (count === 5) {
            clearInterval(intervalID);
        }
    }, 1000);