75 lines
2.9 KiB
JavaScript

const moment = require('moment');
const io = require('./socketio')
let timerInterval;
let duration = moment.duration(7, 'minutes'); // Initial duration
let durationLeft = moment.duration(7, 'minutes'); // durationLeft after the timer has been started
let isPaused = true; // Status of the timer
// Function prototypes
function start() {};
function pause() {};
function reset() {};
function end() {};
function print() {};
function getValues() {};
function start() {
if(isPaused == true && durationLeft.asSeconds() != 0) { // Only allow start if timer ist currently paused and durationLeft is not 0 seconds
console.log("Timer gestartet")
isPaused = false // Set status of the timer
timerInterval = setInterval(() => { // Create Intervalfunction every 1000ms
durationLeft.subtract(1, 'second'); // Subtract a second from from the timer
console.log(print()); // Print durationLeft
io.sockets.emit('timerDurationLeft', print()) // Emit durationLeft to all connected sockets
if(durationLeft.asSeconds() == 0) // End timer if durationLeft == 00:00
end()
}, 1000);
return true
} else
return false
}
function pause() {
if(!isPaused) {
console.log("Timer pausiert");
isPaused = true; // Set status of the timer
clearInterval(timerInterval); // End the execution
return true
} else
return false
}
function reset(newDuration) {
console.log("Timer Zurückgesetzt");
duration = moment.duration(newDuration, 'seconds').clone(); // Set initial duration to received duration in seconds
durationLeft = duration.clone(); // Set durationLeft to the initial duration
io.sockets.emit('timerDurationLeft', print()) // Emit durationLeft to all connected sockets
}
function end() {
isPaused = true // Set status of the timer
clearInterval(timerInterval); // End the execution
io.sockets.emit('timerEnded', print()) // Emit end to all connected sockets
}
function print() {
var minutes = (durationLeft.minutes() < 10) ? "0" + durationLeft.minutes() : durationLeft.minutes(); // Create leading zeros for numbers <10
var seconds = (durationLeft.seconds() < 10) ? "0" + durationLeft.seconds() : durationLeft.seconds(); // Create leading zeros for numbers <10
return minutes + ":" + seconds
}
function getValues() {
return {
isPaused: isPaused,
duration: duration,
durationLeft: durationLeft,
print: print()
};
}
module.exports = {
duration, durationLeft, isPaused, start, pause, reset, end, print, getValues
}