Reputation: 12487
I have this code which works fine. When the countdown gets to 0 it calls the refresh function. However, after the refresh function is complete, I want the countdown timer to start back at 1:00 again. I can't call the countdown timer function because it is within the main onload function. Is the right solution to this to put another function inside $(function() { }
and call that?
var interval = null;
// COUNTDOWN TIMER
$(function() {
var start = "1:00";
interval = setInterval(function() {
var timer = start.split(':');
var minutes = parseInt(timer[0], 10);
var seconds = parseInt(timer[1], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0) {
refresh();
} else {
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
$('.countdown').html(minutes + ':' + seconds);
start = minutes + ':' + seconds;
}
}, 1000);
});
// MY REFRESH FUNCTION
function refresh() {
clearInterval(interval);
$('.countdown').html("Refreshing");
}
Upvotes: 1
Views: 22
Reputation: 90013
Just name the entire routine and you're free to call it:
var interval,
runCountdown = function() {
var start = "0:11";
interval = setInterval(function() {
var timer = start.split(':'),
minutes = parseInt(timer[0], 10),
seconds = parseInt(timer[1], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0) {
refresh();
} else {
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
$('.countdown').html(minutes + ':' + seconds);
start = minutes + ':' + seconds;
}
}, 1000);
},
refresh = function () {
clearInterval(interval);
$('.countdown').html("Refreshing...");
runCountdown();
};
$(function() {
runCountdown();
});
.countdown {
font-size: 3rem;
display: flex;
justify-content: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown"></div>
The same way you call refresh()
from your function, you can call another function from refresh. As long as you give it a reference. A name.
Upvotes: 1