stream-cap/js/timer.js
2022-08-29 13:02:39 -07:00

62 lines
1.9 KiB
JavaScript

// Timekeeping info for the timer
timer_start = 0;
timer_sec = 0;
// Runs once a second to maintain the timer
// Tablutes how long it's been, subtracts that from timer length, then
// updates the HTML element representing the timer
function timer_tick() {
// Don't do anything if a timer isn't running
if (!timer_start) {
return false
}
// Take how long it's been since we started the timer and subtract that
// from the timer duration to get how long is remaining
remain = timer_sec - ((Date.now() - timer_start) / 1000);
// Stop at 0
if (remain < 0) {remain = 0;}
// Update the element
document.getElementById('timer').innerHTML = seconds_to_string(remain);
}
// Utility function to convert seconds to H:MM:SS
function seconds_to_string(seconds) {
hours = Math.floor(seconds / 3600);
minutes = Math.floor((seconds % 3600) / 60);
seconds = Math.floor(seconds % 60);
return String(hours) + ":" +
String(minutes).padStart(2, '0') + ":" +
String(seconds).padStart(2, '0')
}
// Tabluates how many seconds we want on the timer, stores that info, and
// stops a currently running timer
function reset_timer() {
hours = parseInt(document.getElementById('timer_h').value);
minutes = parseInt(document.getElementById('timer_m').value);
seconds = parseInt(document.getElementById('timer_s').value);
total = (minutes * 60) + (hours * 3600) + seconds;
document.getElementById('timer').innerHTML = seconds_to_string(total);
timer_start = 0;
timer_sec = total;
}
// Starts the timer by setting 'now' as the timer start time
function start_timer() {
timer_start = Date.now()
}
// Destroys the timer start time to halt the timer
function stop_timer() {
timer_start = 0;
}
// Start timer interval
setInterval(timer_tick, 1000)