I have written html code with a timer, but I need a script for it to countdown. I researched a lot in the internet and couldn’t find anything that could help me. Maybe someone has experience with this kind of thing here and can help me. I need this timer to start always at the same position 12 minutes 30 seconds when user enters the site it automatically starts going down. If site is refreshed the clock is counting down from the start point which is 12 minutes 30 seconds.
<div id="timer">
<h1 class="pt-5 text-2xl mb-3 font-extralight text-gray-200">Round Closing In</h1>
<div class="text-3xl text-center flex w-full">
<div class="text-xl mr-1 font-extralight text-gray-200">in</div>
<div class="w-24 mx-1 p-2 text-lrgreen rounded-lg">
<div class="text-md font-mono leading-none inline-block" id="hours">0</div>
<div class="font-mono uppercase text-sm leading-none">Hours</div>
</div>
<div class="w-24 mx-1 p-2 text-lrgreen rounded-lg">
<div class="font-mono leading-none inline-block" id="minutes">12</div>
<div class="font-mono uppercase text-sm leading-none">Minutes</div>
</div>
<div class="text-xl mx-1 font-extralight text-gray-200">and</div>
<div class="w-24 mx-1 p-2 text-lrgreen rounded-lg">
<div class="font-mono leading-none inline-block" id="seconds">30</div>
<div class="font-mono uppercase text-sm leading-none">Seconds</div>
</div>
</div>
</div>
2
Answers
This won’t be possible with pure html.
a simple solution is to use local storage which will persist this data on the browser utilising Javascript to display the timer on the page, saving the timer and getting it from local storage.
A simple way to get this from the local storage would be this below line. Then you just need to implement the timer object, then create a function which saves the object as a string to the local storage using the
window.onbeforeunload
hook, effectively saving the timer to the storage before the refresh happens. As well as a simple function to display the timer object properties to the page.Here’s an example you can use, set the
time
variable appropriately, and adjust the timer interval if necessary.