create a timer in javascript

To create a timer in javascript, you can use the setInterval method. This method repeatedly executes a function at a given interval (in milliseconds) until cleared.

Here is an example code block that creates a timer that counts up from 0 and updates every second:

index.tsx
let seconds = 0;
const timer = document.getElementById('timer');

setInterval(() => {
  seconds++;
  timer.innerHTML = seconds;
}, 1000);
138 chars
8 lines

In this example, we first set an initial value of 0 for the seconds variable and select an HTML element with the ID of timer using the getElementById method.

Then, we use setInterval to execute an arrow function every 1000 milliseconds (or 1 second). The arrow function increments the seconds variable and updates the innerHTML of the timer element with the new value of seconds.

You can customize this example to fit your specific timer needs, such as adding a maximum time limit, pausing and resuming the timer, and using different HTML elements to display the timer.

gistlibby LogSnag