DEV Community

Cover image for Simple Stopwatch in plain JS
artydev
artydev

Posted on • Edited on

1

Simple Stopwatch in plain JS

Here is a simple stopwatch, adapted from VanJS doc.

Demo

As you can see, nothing complicated, plain JS, no hooks, no bundling, all this under 1.2kB of library !!!


const {button,span, div, pre, h1} = van.tags

const elapsed = van.state("0.00")

const Stopwatch = () => {
  let id;
  const start = () => id = id || setInterval(() =>
    elapsed.val = (Number(elapsed.val) + 0.01).toFixed(2), 10)
  return span(
    button({onclick: start}, "Start"),
    button({onclick: () => (clearInterval(id), id = 0)}, "Stop"),
    button({onclick: () =>
      (clearInterval(id), id = 0, elapsed.val = "0.00")}, "Reset"),
  )
}

const Screendisplay = () =>  h1(elapsed, " s")

van.add(app, div(
  h1("A Simple Stopwatch"),
  div ({class:"stopwatch"},
    div({class:"content"},
      Screendisplay(),
      Stopwatch())      
    )
  )
)
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (2)

Collapse
 
tao_xin_23db52b1401921dcb profile image
Tao Xin (vanjs.org)

Thanks for sharing the example. Have you considered adding this example to your VanJS series: dev.to/artydev/series/23075?

Collapse
 
artydev profile image
artydev

Done :-)
Thank you Tao

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay