开发者

How to get exact countdown timer in seconds precision even after refreshing page in javascript?

I have created a page which would display the countdown timer of 15 min. So far i have created the countdown timer and it would expire after 15min and displays message 'Time up' but when i refresh the page timer displays the from remaining min not exact remaining seconds.

I need the timer should show the remaining min with seconds precision.

Eg: if the countdown starts and remaining time is 12:55 (12min 55secs) and i refresh the page after 25 seconds it should start showing the countdown timer from 12:30 (12min 30 secs) currently when i refresh the page it starts showing from 13:00. and not 12:30.

Please change the hardcoded date and time if needed. Fiddle sample code here

<h5><div id="divRemainingTime"> </div></h5>


  <script type="text/javascript">
    StartTimer();
    function StartTimer() {
    
                var t1 = new Date();//new Date("Dec 5, 2022 10:00:25");
                var t2 = new Date("Dec 7, 2022 10:35:00");
                var dif = Math.abs(t1.getTime() - t2.getTime()) / 1000;
                var maxTimeoutMin = 15;
                let msDifference = t1 - t2;
                let minutes = Math.floor(msDifference / 1000 / 60);
                minutes = maxTimeoutMin - minutes;
                console.log(minutes);
                if (minutes <= maxTimeoutMin) {
                    var countdown = minutes * 60 * 1000;//first value if for min. i.e 15min
                    var timerId = setInterval(function () {
                        countdown -= 1000;
                        var min = Math.floor(countdown / (60 * 1000));
                        var sec = Math.floor((countdown - (min * 60 * 1000)) / 1000);  //correct
                        if (countdown <= 0) {
                            //alert("30 min!");
                            clearInterval(timerId);
                           
                            $("#divRemainingTime").html("Time up");
                            //doSomething();
                        } else {
                            
                            $("#divRemainingTime").html("00:"+min + " : " + sec);
                            
                        }
    
                    }, 1000); //1000ms. = 1sec.
                }
                else {
                   
                    $("#divRemaining开发者_JAVA百科Time").html("Time up");
                }
            }
 </script>

Help appreciated Thanks

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜