I am trying to add a count up timer to my code. My current code counts down and after the timer reaches 0 it displays news information to a div. This whole process will go on until the page is closed, but I would like to add a stop feature. Meaning that once this code executes 10 times using a count up timer it will completely stop. I tried doing that with the variable session but it doesn’t count up from 1 to 10. It starts at 0 and then jumps up randomly to 67 then 210 425 and so on. How can I accomplished this count up timer from 1 to 10 and then stop the script?
var cycle = 0;
var session = 0;
function countdown() {
var min = 60 * 10;
var max = 60 * 30;
return Math.floor(Math.random() * max) + min;
}
function search() {
$.getJSON('terms.php?json', function(data) {
$('#news_updates').attr("src", data);
});
}
function update() {
if (session === 10) {
alert("done");
}
if (cycle === 0) {
cycle = countdown();
search();
$('#countdown').html('<img src="loading.gif" alt="loading picture"/>');
$('#countup').html(session);
} else {
var minutes = Math.floor(cycle / 60);
var seconds = (cycle % 60);
if (seconds < 10) {
seconds = "0" + seconds;
}
$('#countdown').html(minutes + ':' + seconds);
cycle--;
}
session++;
setTimeout('update()', 1000);
}
Instead of:
try this:
Here’s a jsFiddle for this part:
I also added a return in the
if(session === 0) { ... }, so it stops completely after 10 runs (i.e. not run anothersetTimerand repeat more then expected).