Jump to content

I have a javascript timer but I want the timer to continue to count even if I refresh or restart the browser


Recommended Posts

I am using a countdown timer I've found in google, I just modify some line of codes to make the timer to count up instead of counting down and I want it to not reset if the page is refresh or the browser is restart. From what I know I need to use cookies for this but I don't know how to incorporate it to my code.

 

Here's the code.

 

<html>
<html>
    <head>
        <title>Timer</title>
        <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    </head>
<body>
  <span id="countup">00:00:00</span>
</body>
</html>

<script type="text/javascript">
(function(){
  $(document).ready(function() {
    var time = "00:00:00",
        parts = time.split(':'),
        hours = +parts[0],
        minutes = +parts[1],
        seconds = +parts[2],
        span = $('#countup');
        
    function correctNum(num) {
        return (num<10)? ("0"+num):num;
    }

    var timer = setInterval(function(){
        seconds++;
        if(seconds > 59) {
            minutes++;
            seconds = 0;
          
            if(minutes > 59) {
                hours++;
                seconds = 0;
                minutes = 0;
              
                if(hours >= 24) {
                  alert("timer finished");
                }
            }
        }
        span.text(correctNum(hours) + ":" + correctNum(minutes) + ":" + correctNum(seconds));
    }, 1000); 
  }); 
})()
</script>

 

Edited by KHS
Link to post
Share on other sites

Your script needs a "base time" - the time from which you are counting. Instead of always starting your timer from 00:00:00 you would first calculate the time elapsed from the base time and start from there.

EG base time = 09:00, and it is now 11:10:35, so your timer should start from "02:10:35" when it loads. If you next open the page at midday then the timer shoud start from "03:00:00"

Edited by Barand
Link to post
Share on other sites

Another way of doing is using Javascript and PHP that way it doesn't matter what the user does on the website as the timer will still keep on chiming away.

Here's the javascript:

const getTimeRemaining = (endtime) => {
    var t = Date.parse(endtime) - Date.parse(new Date());
    var seconds = Math.floor((t / 1000) % 60);
    var minutes = Math.floor((t / 1000 / 60) % 60);
    var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
    var days = Math.floor(t / (1000 * 60 * 60 * 24));
    return {
        'total': t,
        'days': days,
        'hours': hours,
        'minutes': minutes,
        'seconds': seconds
    };
};

const myClock = (id, endtime) => {
    var clock = document.getElementById('game' + id);
    var daysSpan = clock.querySelector('.day' + id);
    var hoursSpan = clock.querySelector('.hour' + id);
    var minutesSpan = clock.querySelector('.minute' + id);
    var secondsSpan = clock.querySelector('.second' + id);

    function updateClock() {
        var t = getTimeRemaining(endtime);

        daysSpan.textContent = t.days;
        hoursSpan.textContent = ('0' + t.hours).slice(-2);
        minutesSpan.textContent = ('0' + t.minutes).slice(-2);
        secondsSpan.textContent = ('0' + t.seconds).slice(-2);

        if (t.total <= 0) {
            clearInterval(timeinterval);
        }
    }

    updateClock();
    var timeinterval = setInterval(updateClock, 1000);
};

function ajaxRoutine() {
    var grabDate = "myDate=endDate";

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        //console.log('readyState: ' + xhr.readyState, 'xhr.status: ' + xhr.status);
        if (xhr.readyState === 2) {
            //console.log(xhr.status);
            if (xhr.status === 410) {
                gameover();
            }
        }
        if (xhr.readyState === 4 && xhr.status === 200) {
            var data = JSON.parse(xhr.responseText);
            console.log('data', data);
            console.log('data.home', data.home);
            var opening_day_home = new Date(Date.parse(data.home));
            var team = data.home_opponent + " -vs- " + data.team;

            document.getElementById("countdown_team").textContent = team;
            document.getElementById("opening").textContent = data.home_display;
            team = data.team + " -vs- " + data.away_opponent;
            document.getElementById("countdown_team2").textContent = team;
            document.getElementById("opening2").textContent = data.away_display;
            myClock(1, opening_day_home);
            var opening_day_away = new Date(Date.parse(data.away));
            myClock(2, opening_day_away);

        }
    }; // End of Ready State:

    xhr.open('POST', 'countdown_date.php', true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.send(grabDate);
}

ajaxRoutine();

the php

<?php

/* Makes it so we don't have to decode the json coming from javascript */
header('Content-type: application/json');


$endDate  = filter_input(INPUT_POST, 'myDate');

if ($endDate === 'endDate') {
    $data['team'] = "Tigers";
    $home = new DateTime('2020-03-30 13:10:00', new DateTimeZone("America/Detroit"));
    $data['home'] = $home->format("Y/m/d H:i:s");
    $data['home_display'] = $home->format("l - F j, Y");
    $data['home_opponent'] = "Royals";
    
    $away = new DateTime('2020-03-26 13:10:00', new DateTimeZone("America/Detroit"));
    $data['away'] = $away->format("Y/m/d H:i:s");
    $data['away_display'] = $away->format("l - F j, Y");
    $data['away_opponent'] = "Indians";
    output($data);
}
function errorOutput($output, $code = 500) {
    http_response_code($code);
    echo json_encode($output);
}

/*
 * If everything validates OK then send success message to Ajax / JavaScript
 */

function output($output) {
    http_response_code(200);
    echo json_encode($output);
}

and the HTML

<div id="countdownContainer">
    <div class="teams">
        <h1 id="countdown_team2"></h1>
        <h2 id="opening2"></h2>
    </div>
    <div id="game2">
        <figure class="box">
            <div class="day2"></div>
            <figcaption>Days</figcaption>
        </figure>
        <figure class="box">
            <div class="hour2"></div>
            <figcaption>Hours</figcaption>
        </figure>
        <figure class="box">
            <div class="minute2"></div>
            <figcaption>Minutes</figcaption>
        </figure>
        <figure class="box">
            <div class="second2"></div>
            <figcaption>Seconds</figcaption>
        </figure>
    </div>

    <div class="teams">
        <h1 id="countdown_team"></h1>
        <h2 id="opening"></h2>
    </div>
    <div id="game1">
        <figure class="box">
            <div class="day1"></div>
            <figcaption>Days</figcaption>
        </figure>
        <figure class="box">
            <div class="hour1"></div>
            <figcaption>Hours</figcaption>
        </figure>
        <figure class="box">
            <div class="minute1"></div>
            <figcaption>Minutes</figcaption>
        </figure>
        <figure class="box">
            <div class="second1"></div>
            <figcaption>Seconds</figcaption>
        </figure>
    </div>
</div>

The nice thing about this is it is written in vanilla javascript no jQuery needed. The code isn't the tightest as I just put it up for the current baseball season. Go Tigers! 

Edited by Strider64
Added Info...
Link to post
Share on other sites
This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.