vandan's avatar
Level 13

How to get dynamic timer set in javascript ?

I have static script when how can i convert into dynamic value enter and timer set in laravel

blade file

<input type="text" name="timer">

script file

<script>
    var minutes = 0;
    var seconds = 0;
    function startTimer(duration, display) {
            var timer = duration,
            minutes, seconds;
            setInterval(function() {
                minutes = parseInt(timer / 60, {!! $time->toJson() !!});
                seconds = parseInt(timer % 60, 10);

                minutes = minutes < 10 ? "0" + minutes : minutes;
                seconds = seconds < 10 ? "0" + seconds : seconds;

                display.textContent = minutes + ":" + seconds;

                setCookie("minutes", minutes.toString(), 1);
                setCookie("seconds", seconds.toString(), 1);

                if (--timer < 0) {
                timer = 0;
            }
        }, 1000);
}

window.onload = function() {
    var minutes_data = getCookie("minutes");
    var seconds_data = getCookie("seconds");
    var timer_amount = (60*10); //default
    if (!minutes_data || !seconds_data){
        //no cookie found use default
  }
  else{
        timer_amount = parseInt(minutes_data*60)+parseInt(seconds_data)
  }

    var fiveMinutes = timer_amount,
        display = document.querySelector('#time');
        startTimer(fiveMinutes, display); //`enter code here`
};

function setCookie(cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays*24*60*60*1000));
        var expires = "expires="+d.toUTCString();
        document.cookie = cname + "=" + cvalue + "; " + expires;
} 

function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
} 

thanks

0 likes
2 replies
bobbybouwmann's avatar

Your code is a little bit of a mess! I'm not sure what you're trying to achieve here!

Anyway, first start with getting the timer itself working. I see you have a startTimer function but I don't see it being triggered anywhere. I see you also want to do something with a cookie, skip that part until you have the timer up and running.

This tutorial might help as well: https://www.developerdrive.com/build-countdown-timer-pure-javascript/

And for the cookie part: https://codepen.io/ProfessorSamoff/pen/xqXrgx

1 like
vandan's avatar
Level 13

Thanks for reply i will try but cant understand how to do it

please be more explain how can i do it?

Please or to participate in this conversation.