Interactive Productivity Timer JavaScript, HTML, CSS
👤 Sharing: AI
Okay, here's a basic interactive productivity timer using JavaScript, HTML, and CSS. It includes explanations within the code itself. This is a good starting point; you can customize it further based on your specific needs.
**HTML (index.html)**
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interactive Productivity Timer</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>Productivity Timer</h1>
<div id="timer">
<span id="minutes">25</span>:<span id="seconds">00</span>
</div>
<div class="controls">
<button id="startStop">Start</button>
<button id="reset">Reset</button>
</div>
<div class="settings">
<label for="workTime">Work Time (minutes):</label>
<input type="number" id="workTime" value="25" min="1">
<label for="breakTime">Break Time (minutes):</label>
<input type="number" id="breakTime" value="5" min="1">
<button id="applySettings">Apply</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
```
**CSS (style.css)**
```css
body {
font-family: sans-serif;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f0f0f0;
}
.container {
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
text-align: center;
}
#timer {
font-size: 3em;
margin-bottom: 20px;
}
.controls button {
padding: 10px 20px;
margin: 0 10px;
font-size: 1em;
cursor: pointer;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
}
.controls button:hover {
background-color: #367C39;
}
.settings {
margin-top: 20px;
}
.settings label {
display: block;
margin-bottom: 5px;
}
.settings input[type="number"] {
width: 60px;
padding: 5px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
.settings button {
padding: 8px 16px;
font-size: 0.9em;
cursor: pointer;
background-color: #008CBA;
color: white;
border: none;
border-radius: 5px;
}
.settings button:hover {
background-color: #00546B;
}
```
**JavaScript (script.js)**
```javascript
// Get references to HTML elements
const minutesDisplay = document.getElementById('minutes');
const secondsDisplay = document.getElementById('seconds');
const startStopButton = document.getElementById('startStop');
const resetButton = document.getElementById('reset');
const workTimeInput = document.getElementById('workTime');
const breakTimeInput = document.getElementById('breakTime');
const applySettingsButton = document.getElementById('applySettings');
let timerInterval; // Variable to store the interval ID
let timeLeft; // Time left in seconds
let isRunning = false; // Flag to track if the timer is running
let isWorkTime = true; // Flag to indicate if it's work or break time
// Function to update the timer display
function updateDisplay() {
const minutes = Math.floor(timeLeft / 60);
const seconds = timeLeft % 60;
minutesDisplay.textContent = String(minutes).padStart(2, '0'); // Add leading zero if needed
secondsDisplay.textContent = String(seconds).padStart(2, '0');
}
// Function to start the timer
function startTimer() {
if (!isRunning) {
isRunning = true;
startStopButton.textContent = 'Pause'; // Change button text
timerInterval = setInterval(() => {
timeLeft--;
if (timeLeft < 0) {
clearInterval(timerInterval); // Stop the timer when time is up
isRunning = false;
startStopButton.textContent = 'Start'; // Reset button text
// Switch between work and break
isWorkTime = !isWorkTime;
if (isWorkTime) {
timeLeft = parseInt(workTimeInput.value) * 60; // Reset to work time
alert("Work time started!");
} else {
timeLeft = parseInt(breakTimeInput.value) * 60; // Reset to break time
alert("Break time started!");
}
updateDisplay(); // Update the display after switching
startTimer(); // Automatically restart the timer
} else {
updateDisplay(); // Update the display every second
}
}, 1000); // Update every 1000 milliseconds (1 second)
} else {
// Pause the timer
clearInterval(timerInterval);
isRunning = false;
startStopButton.textContent = 'Start';
}
}
// Function to reset the timer
function resetTimer() {
clearInterval(timerInterval); // Stop the timer if running
isRunning = false;
startStopButton.textContent = 'Start';
// Reset to work time
isWorkTime = true;
timeLeft = parseInt(workTimeInput.value) * 60;
updateDisplay();
}
// Function to apply settings
function applySettings() {
const workTime = parseInt(workTimeInput.value);
const breakTime = parseInt(breakTimeInput.value);
if (isNaN(workTime) || isNaN(breakTime) || workTime <= 0 || breakTime <= 0) {
alert("Please enter valid work and break times (numbers greater than 0).");
return;
}
// Stop the timer before applying settings
clearInterval(timerInterval);
isRunning = false;
startStopButton.textContent = 'Start';
//Apply new settings
isWorkTime = true;
timeLeft = workTime * 60;
updateDisplay();
}
// Initial setup: Set initial time and display
applySettings(); // Apply settings to set initial work time
// Event listeners
startStopButton.addEventListener('click', startTimer);
resetButton.addEventListener('click', resetTimer);
applySettingsButton.addEventListener('click', applySettings);
```
**Explanation:**
1. **HTML (index.html):**
* Sets up the basic structure of the page: title, links to CSS and JavaScript.
* Creates a `div` with class `container` to hold all the content.
* Contains elements for:
* Displaying the timer (`#timer`, `#minutes`, `#seconds`).
* Start/Stop and Reset buttons (`#startStop`, `#reset`).
* Input fields for work and break times (`#workTime`, `#breakTime`).
* A button to apply the settings (`#applySettings`).
2. **CSS (style.css):**
* Provides basic styling to make the timer look presentable. This includes centering the content, setting font, colors, and some basic layout. Feel free to customize this to your liking!
3. **JavaScript (script.js):**
* **`// Get references to HTML elements`**: Selects the HTML elements that the JavaScript code will interact with using `document.getElementById()`.
* **`let timerInterval;`**: A variable to hold the ID of the `setInterval` function. This is important for stopping the timer later.
* **`let timeLeft;`**: Stores the remaining time in seconds.
* **`let isRunning = false;`**: A boolean flag that indicates whether the timer is currently running or not.
* **`let isWorkTime = true;`**: A boolean flag that indicates whether it's currently work time or break time.
* **`updateDisplay()` Function:**
* Calculates the minutes and seconds from `timeLeft`.
* Uses `String(minutes).padStart(2, '0')` to ensure that minutes and seconds always have two digits (e.g., "05" instead of "5").
* Updates the content of the `#minutes` and `#seconds` elements to display the time.
* **`startTimer()` Function:**
* Checks if the timer is already running (`!isRunning`).
* If not running:
* Sets `isRunning` to `true`.
* Changes the text of the `#startStop` button to "Pause".
* Uses `setInterval()` to call a function every 1000 milliseconds (1 second). This function:
* Decrements `timeLeft`.
* Checks if `timeLeft` is less than 0 (timer has reached 0).
* If `timeLeft` is less than 0:
* `clearInterval(timerInterval)`: Stops the timer.
* Switches `isWorkTime` to the opposite value (work -> break, break -> work).
* Sets `timeLeft` to the appropriate work or break time from the input fields.
* Calls `updateDisplay()` to show the new time.
* Calls `startTimer()` to automatically restart the timer.
* If `timeLeft` is not less than 0:
* Calls `updateDisplay()` to update the display.
* If already running (timer is paused):
* `clearInterval(timerInterval)`: Stops the timer.
* Sets `isRunning` to `false`.
* Changes the text of the `#startStop` button to "Start".
* **`resetTimer()` Function:**
* Stops the timer if it's running.
* Resets `isRunning` to `false`.
* Resets `isWorkTime` to `true`.
* Sets `timeLeft` back to the work time from the input field.
* Calls `updateDisplay()` to update the display.
* **`applySettings()` Function:**
* Gets the work and break times from the input fields.
* Validates the input to ensure they are valid numbers greater than 0.
* Stops the timer if running.
* Sets the initial `timeLeft` based on the work time.
* Calls `updateDisplay()` to update the display.
* **Event Listeners:**
* Attaches event listeners to the buttons:
* `startStopButton`: Calls `startTimer()` when clicked.
* `resetButton`: Calls `resetTimer()` when clicked.
* `applySettingsButton`: Calls `applySettings()` when clicked.
* `applySettings()` is also called once at the end of the script to initialize the timer with the default work time.
**How to use:**
1. Save the HTML, CSS, and JavaScript code as `index.html`, `style.css`, and `script.js` respectively in the *same* directory.
2. Open `index.html` in your web browser.
3. Set your desired work and break times using the input fields.
4. Click "Apply" to update the timer's settings.
5. Click "Start" to begin the timer. Click "Pause" to pause.
6. Click "Reset" to reset the timer to the work time.
This is a basic example. You can expand on this by adding features like:
* Sound notifications when the timer switches between work and break.
* Visual progress bar.
* More sophisticated settings (e.g., number of work/break cycles, auto-start).
* Local storage to remember the user's settings.
* Task list integration
Remember to test your code thoroughly and consider edge cases to ensure it works reliably.
👁️ Viewed: 7
Comments