Video Tutorial - Timers, Countdowns and Stopwatches

  • Thread starter
  • Admin
  • #1

Jaxel

Administrator

Package JS:
Code:
var countdown = null;
var stopwatch = null;

Page HTML:
Code:
<b>Stopwatch:</b>
<div class="stopwatch"></div>

<b>Countdown:</b>
<div class="countdown"></div>
Page JS:
Code:
clearInterval(countdown);
clearInterval(stopwatch);

$('.countdown').text(calcTimer(docData['count_o']));
$('.stopwatch').text(calcTimer(docData['watch_o']));

if (docData['count_s'] > 0)
{
    countdown = setInterval(function()
    {
        time = parseInt(docData['count_e']) + parseInt(docData['count_o']) - new Date().getTime();
        $('.countdown').text(calcTimer(time));
    }, 100);
}

if (docData['watch_s'] > 0)
{
    stopwatch = setInterval(function()
    {
        time = new Date().getTime() - parseInt(docData['watch_e']) + parseInt(docData['watch_o']);
        $('.stopwatch').text(calcTimer(time));
    }, 100);
}

function calcTimer(time)
{
    let neg = (time < 0) ? '- ' : '';
    time = Math.abs(time / 1000);
    
    hours = (Math.floor(time / 3600)).toString().padStart(2, '0');
    minutes = (Math.floor(time % 3600 / 60)).toString().padStart(2, '0');
    seconds = (time % 60).toFixed(1).toString().padStart(4, '0');
    
    return neg + hours + ' : ' + minutes + ' : ' + seconds;
}