Skip to content

Instantly share code, notes, and snippets.

@shritesh
Last active November 15, 2023 03:06
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shritesh/5629a28a0b9f1e8c31ea11912100fb1f to your computer and use it in GitHub Desktop.
Save shritesh/5629a28a0b9f1e8c31ea11912100fb1f to your computer and use it in GitHub Desktop.
Alpine.js Stopwatch
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Alpine Stopwatch</title>
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.js" defer></script>
</head>
<body>
<div x-data="{
start: null,
current: null,
stop: null,
interval: null
}">
<button x-show="!start" @click="
start = Date.now()
current = start
interval = setInterval(() => {current = Date.now()}, 100)
">Start</button>
<div x-show="current">
<button @click="
current = null
stop = Date.now()
clearInterval(interval)
">Stop</button>
<p><span x-text="(current - start) / 1000"></span> Seconds</p>
</div>
<div x-show="stop">
<button @click="
start = null
stop = null
">Reset</button>
<p><span x-text="(stop - start) / 1000"></span> Seconds</p>
</div>
</div>
</body>
</html>
@nelsonic
Copy link

We used @shritesh's superb gist as the basis for our Alpine.js + Tailwind CSS Stopwatch:
https://dwyl.github.io/learn-alpine.js/stopwatch.html
alpine-tailwind-stopwatch

Code: https://github.com/dwyl/learn-alpine.js/blob/bff0a966dda25f2d68592b30501ecdec1cc1282c/stopwatch.html
Thanks again! ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment