In the below I have a countup timer that hours, minutes and seconds, but I would like this to only show higher value that is not 0 and then append the respective naming, i.e.
- If count up is between 00:00:00 and 00:00:59 I would like it to show i.e : 49 seconds
- When between 00:01:00 and 00:59:59 I would like it to display i.e : 26 minutes
- When between 00:59:59 and 23:59:59 I would like it to display i.e : 13 hours
(If it is possible I would even like it to show days, but not necessary)
Is this even possible, and if so, how can I achieve this?
My initial script:
function startCount() {
setInterval(function() {
$(".count").text(function() {
var val = $(this).data("secs");
$(this).data("secs", val);
return new Date(val * 1000).toISOString().substr(11, 8);
})
}, 1000);
}
startCount()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="count" data-secs="89895"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Math problem, hope this is the desired output.
function startCount() {
$('.count').data('initial', new Date().getTime() - ($('.count').data('secs') || 0) * 1000);
setInterval(function() {
$(".count").text(function() {
const diff = new Date().getTime() - $(this).data('initial');
if (Math.floor(diff / (24 * 3600000)) > 0) {
return Math.floor(diff / (24 * 3600000)) 'd'; // more than 1 day
} else if (Math.floor(diff / 3600000) > 0) {
return Math.floor(diff / 3600000) 'h'; // more than 1 hour
} else if (Math.floor(diff / 60000) > 0) {
return Math.floor(diff / 60000) 'm'; // more than 1 minute
} else {
return Math.floor(diff / 1000) 's';
}
})
}, 1000);
}
startCount()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="count" data-secs="0"></div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>