Reputation: 1807
I have countdown function using Javascript/jQuery.
function countdownto(target, time, callback) {
var finish = new Date(time);
var s = 1000,
m = s * 60,
h = m * 60,
d = h * 24;
(function timer() {
var now = new Date();
var dist = finish - now;
var days = Math.floor(dist / d),
hours = Math.floor((dist % d) / h),
minutes = Math.floor((dist % h) / m),
seconds = Math.floor((dist % m) / s);
var timestring = days + 'days ' + hours + 'hrs ' + minutes + 'mins ' + seconds + 'seconds ';
target.html(timestring)
if (dist > 0) {
setTimeout(timer, 1000);
} else {
callback()
}
})()
}
// 10 seconds into the future
var time = "08/02/2021 17:05:00";
var time2 = "08/02/2021 17:33:00";
// countdown function call
countdownto($('#countdown'), time, function(){
console.log('tadaaa')
countdownto($('#countdown2'), time2, function(){
console.log('tadaaa')
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="countdown"></div>
<div id="countdown2"></div>
Now I need to add function interval second there to get the current interval time.
My question is: how to get interval time inside this function:
countdownto($('#countdown'), time, function(){
console.log('tadaaa')
alert(time); // <-- how to get interval time? Alert not appear, as I know here when the countdown finish.
countdownto($('#countdown2'), time2, function(){
console.log('tadaaa')
})
})
Upvotes: 0
Views: 133
Reputation: 5735
Technically, you already have the time as string inside your global time
variable. If you want to pass it to the callback anyway, you have to pass it where the callback is invoked:
function countdownto(target, time, callback) {
var finish = new Date(time);
var s = 1000,
m = s * 60,
h = m * 60,
d = h * 24;
(function timer() {
var now = new Date();
var dist = finish - now;
var days = Math.floor(dist / d),
hours = Math.floor((dist % d) / h),
minutes = Math.floor((dist % h) / m),
seconds = Math.floor((dist % m) / s);
var timestring = days + 'days ' + hours + 'hrs ' + minutes + 'mins ' + seconds + 'seconds ';
target.html(timestring)
if (dist > 0) {
setTimeout(timer, 1000);
} else {
callback(finish)
}
})()
}
// 10 seconds into the future
var time = "08/02/2021 17:05:00";
var time2 = "08/02/2021 17:33:00";
// countdown function call
countdownto($('#countdown'), time, function(time){
console.log('tadaaa')
alert(time); // <-- how to get interval time? Alert not appear, as I know here when the countdown finish.
countdownto($('#countdown2'), time2, function(){
console.log('tadaaa')
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="countdown"></div>
<div id="countdown2"></div>
Upvotes: 2