Skip to content

Instantly share code, notes, and snippets.

@tayiorbeii
Created December 11, 2023 21:13
Show Gist options
  • Save tayiorbeii/3e5e461bfd9e1e33a577b9c9cc7e0541 to your computer and use it in GitHub Desktop.
Save tayiorbeii/3e5e461bfd9e1e33a577b9c9cc7e0541 to your computer and use it in GitHub Desktop.
import "@johnlindquist/kit"
// Name: stopwatch
let time = 0;
let timerId = null;
let isPaused = false;
function formatTime(timeInSeconds) {
let hours = Math.floor(timeInSeconds / 3600);
let minutes = Math.floor((timeInSeconds - (hours * 3600)) / 60);
let seconds = timeInSeconds - (hours * 3600) - (minutes * 60);
// Pad to two digits
minutes = ('0' + minutes).slice(-2);
seconds = ('0' + seconds).slice(-2);
// Format time
if (hours > 0) {
hours = ('0' + hours).slice(-2);
return `${hours}:${minutes}:${seconds}`;
} else {
return `${minutes}:${seconds}`;
}
}
async function updateWidget() {
await stopwatch.setState({
time: formatTime(time),
startPauseButtonText: isPaused || !timerId ? 'Start' : 'Pause',
});
}
let stopwatch = await widget(`
<div class="p-5 bg-black bg-opacity-50 text-white flex flex-col items-center justify-center space-y-5 draggable">
<button id="time"><h1 class="text-7xl p-5 whitespace-nowrap">{{time}}</h1></button>
<div class="flex space-x-4">
<button id="startPauseButton" class="border px-2 py-1 min-w-20">{{startPauseButtonText}}</button>
<button id="resetButton" class="border px-2 py-1 min-w-20">Reset</button>
</div>
</div>
`, {
resizable: true,
alwaysOnTop: true,
useContentSize: true,
opacity: 0.6,
width: 282,
height: 214,
draggable: true,
});
stopwatch.onClick((event) => {
if (event.targetId === "startPauseButton" || event.targetId === "time") {
if (timerId) {
clearInterval(timerId);
timerId = null;
isPaused = true;
} else {
timerId = setInterval(() => {
time++;
updateWidget();
}, 1000);
isPaused = false;
}
updateWidget();
}
else if (event.targetId === "resetButton") {
if (timerId) {
clearInterval(timerId);
timerId = null;
}
time = 0;
isPaused = false;
updateWidget();
}
});
// keydown('shift option space', () => {
// if (timerId) {
// clearInterval(timerId);
// timerId = null;
// isPaused = true;
// } else {
// timerId = setInterval(() => {
// time++;
// updateWidget();
// }, 1000);
// isPaused = false;
// }
// updateWidget();
// });
// keydown('shift option x', () => {
// if (timerId) {
// clearInterval(timerId);
// timerId = null;
// }
// time = 0;
// isPaused = false;
// updateWidget();
// });
updateWidget();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment