Multiple stopwatch counters via jQuery with start date/time


HTML • JavaScript • JQuery

jQuery

$(document).ready(function() {
	$(".elapsed").each(function(index) {	
		var startDatetimeSTR = $(this).data('startdatetime');
		var startDatetime = new Date(startDatetimeSTR);
		
		// Update the counter every second
		var intervalId = setInterval(function() {
			var now = new Date();
			var distance =  now.getTime() - startDatetime.getTime();
			
			// Calculate days, hours, minutes, and seconds
			var days = Math.floor(distance / (1000 * 60 * 60 * 24));
			var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
			var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
			var seconds = Math.floor((distance % (1000 * 60)) / 1000);

			// Update the counter display
			$(this).html(days + "d " + hours + "h " + minutes + "m " + seconds + "s");

			// Stop the counter if the target date is reached
			if (distance < 0) {
				clearInterval(intervalId);
			}
		}.bind(this), 1000); // Update every 1 second
  	});
});

HTML

<div class="elapsed" data-startdatetime="2024-10-16 00:00:00">-</div>
<div class="elapsed" data-startdatetime="2024-10-14 09:35:00">-</div>
<div class="elapsed" data-startdatetime="2024-10-15 14:20:00">-</div>

Written by fbrefere001

Posted by fbrefere001 on Wednesday October 16, 2024