-1

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);
};
Brett Caswell
  • 732
  • 1
  • 4
  • 16
  • 5
    Post your current code so we can see what you did. – Morne Mar 05 '15 at 14:23
  • 1
    Whats a div got to do with generating random numbers? This question makes no sense. Post some code. – Jamiec Mar 05 '15 at 14:24
  • 1
    You could do a timeout that then stops the interval given the handle it returned when you created. – Benjamin Trent Mar 05 '15 at 14:25
  • I smell a school project... Read [this informative web page](http://www.w3schools.com/jsref/met_win_clearinterval.asp) – Jamie Barker Mar 05 '15 at 14:27
  • What you are looking for is `clearInterval`. Keep track of how many times the `setInterval` call back has fired and call `clearInterval` after the 5th time to stop it firing again. Just note that the timing isn't going to be perfect, if that's important to you. – Matt Burland Mar 05 '15 at 14:29
  • Thank you all for answers. You helped me a lot :). clearInterval is what I was looking for :). – Nemanja Neca Mar 05 '15 at 17:10

4 Answers4

3

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);
Matt Burland
  • 42,488
  • 16
  • 89
  • 156
0

Something hastily written, but what you want to do is keep track of your interval handle and then clear it. You can do this with a setTimeout

var forXsecs = function(period, func) {
  var handle = setInterval(func, 1000);
  setTimeout(function() { clearInterval(handle); }, period * 1000);
}

The timing is not perfect. Matt's answer would also work.

Another option is a slight change on Matt's answer that removes setInterval and just uses timeouts.

var count = 0;
var forXsecs = function(period, func) {
    if(count < period) {
        func();
        count++;
        setTimeout(function() {forXsecs(period, func);}, 1000);
    } else {
        count = 0; //need to reset the count for possible future calls
    }
}
Benjamin Trent
  • 6,494
  • 3
  • 31
  • 40
0

If you just want to simply let it run once each second and that 5 times you can do it like this:

HTML:

<div id="5seconds"></div>

JS:

var count= 0;
setInterval(function(){
    if(count < 5){
        document.getElementById('5seconds').innerHTML = Math.random();
        count++
    }
},1000);

This will generate a random number each second. until 5 seconds have passed

frogatto
  • 26,401
  • 10
  • 73
  • 111
zeropublix
  • 1,177
  • 11
  • 21
0

you should use clearInterval to stop the timer.

To do so, you pass in the id(or handle) of a timer returned from the setInterval function (which creates it).

I recommend clearing the interval timer (using clearInterval) from within the function being executed.

var elm = document.querySelector("div.container");
var cnt = 0;
var timerID;

function generateNumber()
{
  cnt += 1;
  elm.innerText = cnt;
  if (cnt >= 5) {
    window.clearInterval(timerID);
    
  }
}

timerID = window.setInterval(generateNumber, 1000);
.container {display:block; min-width:5em;line-height:5em;min-height:5em;background-color:whitesmoke;border:0.1em outset whitesmoke;}
<label>1s Interval over 5s</label>  
<div class="container"></div>
Brett Caswell
  • 732
  • 1
  • 4
  • 16