-1

please kindly help me with my countdown code its restarting everything I refresh the page. Also, the minutes and seconds are counting together at the same time

Below is my current javascript code;

function startTimer(duration, display) {
    var start = Date.now(),
        diff,
        minutes,
        seconds;
    function timer() {
        // get the number of seconds that have elapsed since 
        // startTimer() was called
        diff = duration - (((Date.now() - start) / 1000) | 0);

        // does the same job as parseInt truncates the float
        minutes = (diff / 60 * 60) | 0;
        seconds = (diff % 60) | 0;

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

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

        if (diff <= 0) {
            // add one second so that the count down starts at the full duration
            // example 05:00 not 04:59
            start = Date.now() + 1000;
        }
    };
    // we don't want to wait a full second before the timer starts
    timer();
    setInterval(timer, 1000);
}

window.onload = function () {
    var fiveMinutes = 60 * 2,
        display = document.querySelector('#time');
    startTimer(fiveMinutes, display);
};
<div id="time"></div>

Kindly help me out........ Thanks in advance

madalinivascu
  • 32,064
  • 4
  • 39
  • 55

2 Answers2

1

Here you go. It's a bit messy, but I was in a hurry, so you have to tidy it up yourself ;)

I used local storage to store the time and when you refresh it checks for local storage and loads the time that's left accordingly.

HTML:

<div id="time"></div>

JS:

function countDown(minutes, seconds) {
  var currentTime;

  function twoDigits(n) {
    return (n <= 9 ? '0' + n : n);
  }

  function updateTimer() {
    msLeft = endTime - (+new Date);
    time = new Date(msLeft);
    hours = time.getUTCHours();
    mins = time.getUTCMinutes();
    currentTime = (hours ? hours + ':' + twoDigits(mins) : mins) + ':' + twoDigits(time.getUTCSeconds());
    localStorage.setItem('timer', currentTime);
    $('#time').text(currentTime);
    countDownTimer = setTimeout(updateTimer, time.getUTCMilliseconds() + 500);
  }

  endTime = (+new Date) + 1000 * (60 * minutes + seconds) + 500;
  updateTimer();
}

if (localStorage.getItem('timer')) {
  localTime = localStorage.getItem('timer');
  var minutes = parseInt(localTime.substr(0, localTime.indexOf(':')));
  var seconds = parseInt(localTime = localTime.split(':')[1]);

  countDown(minutes, seconds);
} else {
  countDown(120, 0);
}

Fiddle

erol_smsr
  • 1,454
  • 4
  • 24
  • 49
0

You can use localStorage or Cookie. Cookie is best used with Server-Side communication, where you can monitor user activity if they try to cheat on countdown. LocalStorage is on the Client-Side, so the client can manipulate at their will. However, both ways are possible, please have a look at below sample that is quiet messy, sorry. Hope this helps you. By the way, cookies won't work on localhost, your page should run on node.js or on similar environment.

HTML:

<div id="time"></div>

JS

var _time = 0;
var _cookie_val = {hours:"", minutes:"", seconds:""};

//change seconds to HH:MM:SS
//http://stackoverflow.com/questions/6312993/javascript-seconds-to-time-string-with-format-hhmmss
String.prototype.toHHMMSS = function () {
    var sec_num = parseInt(this, 10);
    var hours   = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var seconds = sec_num - (hours * 3600) - (minutes * 60);
    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    return {hours:hours, minutes:minutes, seconds:seconds};
}


//get Cookie
let _getCookie = function(args) {
  var _cookie_Val = "; " + document.cookie;
  var _splits = _cookie_Val.split("; " + args + "=");
  if (_splits.length==2) return _splits.pop().split(";").shift();
}

//set cookie
let _cookie = function (args) {
  document.cookie = "_hours=" + args.args_toHHMMSS.hours;
  document.cookie = "_minutes=" + args.args_toHHMMSS.minutes;
  document.cookie = "_seconds=" + args.args_toHHMMSS.seconds;
  document.cookie = "args=" + args.args;
};


var _timer = function (args) {
  //set _time to args if _getCookie('args') is undefined or empty
  var _time = _getCookie("args") || args;

  //convert val to string and set cookie
  _cookie({args_toHHMMSS: _time.toString().toHHMMSS(), args: _time});

  //get cookie    _getCookie(_hours || _minutes || _seconds || args)
  // console.log(_getCookie("args").toString().toHHMMSS());
  var update_print = _getCookie("_hours") + ":" +
                     _getCookie("_minutes") + ":" +
                     _getCookie("_seconds");
  document.querySelector('#time').textContent = update_print;


  //start interval
  let _interval = setInterval( function(){

    //convert val to string and set cookie
    _cookie({args_toHHMMSS: _time.toString().toHHMMSS(), args: _time});

    //get cookie    _getCookie(_hours || _minutes || _seconds || args)
    var update_print = _getCookie("_hours") + ":" +
                       _getCookie("_minutes") + ":" +
                       _getCookie("_seconds");
    document.querySelector('#time').textContent = update_print;


    //stop interval when time reaches 0
    if(_time <= 0){
      //finite loop
      clearInterval(_interval);

      //infinite loop
      //_time = args;

    }else{ _time--; }
  },1000);
}



//onload this function will be executed
window.onload = () => {
  var seconds = 5; //enter the desired minute. e.g 300 for 5 min
  _timer(seconds); //call _timer with argument seconds
};
Michael Seltene
  • 543
  • 1
  • 5
  • 17