Back to all resources
JavaScript
progress bar
date manipulation
real-time updates

Progress Bar Timer

By Digipop
This JavaScript code snippet is designed to visually represent the progress of time between two specified dates using a progress bar. The code utilizes HTML elements identified by their IDs, "progressBar" for the container and "progress" for the progress indicator itself.

The endDate and startDate variables define the start and end times for the progress calculation. These are hardcoded to specific dates and times. The addFrame function is the core of this script, which calculates the elapsed time from the start date to the current time and updates the width of the progress bar accordingly.

The function addFrame is executed every 100 milliseconds, as set by setInterval(addFrame, 100). Within this function:

  • It first fetches the current time.
  • It then calculates the total duration (distanceWhole) and the remaining duration (distanceLeft) in milliseconds between the current time and the end date.
  • These durations are converted into minutes (minutesLeft and minutesTotal).
  • The percentage of time elapsed (result) is calculated and used to update the width of the progress bar element (progress.style.width).

The progress bar width is updated in real-time to reflect the percentage of time elapsed from the start date to the current time, relative to the total duration between the start and end dates. If the calculated result is less than 100, the progress bar's width is updated; otherwise, it remains at its maximum width.