So I'm just starting to learn JavaScript, like its syntax and logic, therefore I'm still not implementing anything on a web page, just playing with the console before doing any web development with JS.
There's this function I'd like to implement, a restart function where you can start the stopwatch again after having restarted it, which I quite haven't figured out how to do so
Here's the run() function with the logic of all necessary inputs to control the stopwatch (such as a start key, a pause/resume key, a stop and finally a restart key:
function run() {
const rl = readline.createInterface({
input: process.stdin
});
rl.on('line', (input) => {
if (input.toLowerCase() === 'i') {
if (!running) {
if (restarted && paused) {
seconds = 0;
minutes = 0;
hours = 0;
hundredths = 0;
laps = [];
restarted = false;
// restartTime = Date.now(); not sure if this even works as I expect it to.
}
startStopwatch();
}
} else if (input.toLowerCase() === 'p' && running) {
paused = !paused;
console.log('Stopwatch is paused.');
} else if (input.toLowerCase() === 'd' && running) {
running = false;
rl.close();
console.log('Stopwatch has been stopped.');
} else if (input.toLowerCase() === 'l' && running && !paused) {
recordLaps();
} else if (input.toLowerCase() === 'v' && paused) {
showLaps();
} else if (input.toLowerCase() === 'r' && paused) {
restarted = true;
console.log('Stopwatch has been restarted.');
} else if (input.toLowerCase() === 'i' && restarted && paused) {
startStopwatch();
}
});
}
Here's what the Stopwatch() function looks like, also I showed the startStopwatch() func.
async function Stopwatch() {
let startTime = Date.now();
while (running) {
if (!paused) {
let currentTime = Date.now(),
elapsedTime = currentTime - startTime;
hundredths = Math.floor(elapsedTime % 1000 / 10)
let Hours = getTimeFormat(hours),
Minutes = getTimeFormat(minutes),
Seconds = getTimeFormat(seconds),
Hundredths = getTimeFormat(hundredths);
await clearConsole();
console.log(`${Hours}:${Minutes}:${Seconds}.${Hundredths}`);
if (elapsedTime >= 1000) {
startTime = currentTime;
seconds++;
if (seconds === 60) {
seconds = 0;
minutes++;
if (minutes === 60) {
minutes = 0;
hours++;
}
}
}
}
await sleep(1);
}
}
async function startStopwatch() {
running = true;
await clearConsole();
await Stopwatch();
}