Reputation: 525
how do i add a start, stop and reset button to the countdown timer
var cycle = 0;
function countdown()
{
var min = 60*5;
var max = 60*7;
return Math.floor(Math.random()*max) + min;
}
function search()
{
$.getJSON('json', function(data)
{
$('#fullurl').attr("src", 'mywebsite' + data);
}
);
}
function update()
{
if (cycle == 0)
{
cycle = countdown();
search();
$('#countdown').html('...');
}
else
{
var minutes = Math.floor(cycle / 60);
var seconds = (cycle % 60);
if (seconds < 10) seconds = "0" + seconds;
$('#countdown').html(minutes + ':' + seconds);
cycle--;
}
setTimeout('update()', 1000);
}
Upvotes: 0
Views: 1271
Reputation: 16591
I don't really see any HTML markup in the code above, and it looks a bit mysterious and incomplete to me. My guess would be to call update()
on start, cancel the timeout on stop and reset your variables on reset.
var cycle = 0;
var timer_id = null;
function countdown()
{
var min = 60*5;
var max = 60*7;
return Math.floor(Math.random()*max) + min;
}
function search()
{
$.getJSON('json', function(data)
{
$('#fullurl').attr("src", 'mywebsite' + data);
}
);
}
function update()
{
if (cycle == 0)
{
cycle = countdown();
search();
$('#countdown').html('...');
}
else
{
var minutes = Math.floor(cycle / 60);
var seconds = (cycle % 60);
if (seconds < 10) seconds = "0" + seconds;
$('#countdown').html(minutes + ':' + seconds);
cycle--;
}
timer_id = setTimeout('update()', 1000);
}
function stop()
{
if(timer_id)
{
clearTimeout(timer_id);
timer_id = null;
}
}
function reset()
{
stop();
cycle = 0;
//reset your HTML elements, just guessing
$('#countdown').html('');
$('#fullurl').attr("src", '');
}
//jQuery ready function
$(function(){
//assuming you add some buttons with IDs to your markup
$('#btnStart').click(update);
$('#btnStop').click(stop);
$('#btnReset').click(reset);
});
Upvotes: 3