pomodoro in javascript

Here is a simple implementation of the Pomodoro timer in JavaScript:

index.tsx
// Set timer for 25 minutes
let workMinutes = 25;

// Set timer for 5 minutes break
let breakMinutes = 5;

// Keep track of whether timer is running
let isTimerRunning = false;

// Get elements from DOM
const workTimerElement = document.getElementById('work-timer');
const breakTimerElement = document.getElementById('break-timer');
const startButton = document.getElementById('start-button');
const resetButton = document.getElementById('reset-button');

// Initialize timer text to work timer
workTimerElement.textContent = `${workMinutes}:00`;

// Start timer
startButton.addEventListener('click', () => {
  if (!isTimerRunning) {
    isTimerRunning = true;
    startTimer(workMinutes, workTimerElement);
  }
});

// Reset timer
resetButton.addEventListener('click', () => {
  isTimerRunning = false;
  workTimerElement.textContent = `${workMinutes}:00`;
  breakTimerElement.textContent = `${breakMinutes}:00`;
});

// Timer function
function startTimer(minutes, element) {
  let seconds = 60;
  const interval = setInterval(() => {
    seconds--;
    if (seconds < 0) {
      minutes--;
      seconds = 59;
      if (minutes < 0) {
        clearInterval(interval);
        isTimerRunning = false;
        if (element === workTimerElement) {
          startTimer(breakMinutes, breakTimerElement);
        } else if (element === breakTimerElement) {
          workTimerElement.textContent = `${workMinutes}:00`;
          breakTimerElement.textContent = `${breakMinutes}:00`;
        }
      }
    }
    element.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  }, 1000);
}
1623 chars
56 lines

This code sets up two timers - one for work time and one for break time. The default values for these timers are 25 minutes for work and 5 minutes for break. The startTimer function is called when the user clicks the start button, and it starts counting down from the specified number of minutes. When the timer reaches 0, it switches to the other timer. The user can reset the timer at any time by clicking the reset button.

gistlibby LogSnag