Adding "localStorage" To Countdown Timer

Discussion in 'JavaScript' started by gregdavidson, Jul 3, 2015.

  1. #1
    I added this countdown timer to my One Time Offer page and it resets every single time somebody reloads the page. Somebody told me that I need to add "localStorage" to the script to stop it from doing that. What lines of coding do I need to add to the script below?

    <script>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) | 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 thirtyMinutes = 60 * 30,
    display = document.querySelector('#time');
    startTimer(thirtyMinutes, display);
    };</script>
    Code (JavaScript):
     
    gregdavidson, Jul 3, 2015 IP
  2. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #2
    Localstorage can be just as easily slapped aside as that script - using scripting to show the time remaining is "cute", but is NOT secure or functional -- as per your other thread, this is stuff you should store on the SERVER using sessions, tracking the IP address, and a whole host of far more secure and far harder to bypass methodology.

    Scripting is for enhancing page functionality, NOT for providing said functionality. It's a cute toy for showing what's remaining, but should NOT be relied upon for TRACKING what's remaining.

    Using PHP for example you'd just create a session, store in the session when the offer expires, and if they revisit the page load the time remaining from the session server-side for the scripting to show the countdown from that point. Of course the user clears their cookies they can slap that session aside and be treated as a new user, which is where tracking them in a database via IP address and maybe UA string -- mating in some form of e-mail validation would be a far more robust solution.

    Scripttardery is NOT the answer for this sort of thing since it runs client-side, giving it all the security of parking a Benzo in downtown Oakland with the windows rolled down and walking away.
     
    deathshadow, Jul 4, 2015 IP