1

var date = new Date;
var s = date.getSeconds();
var m = date.getMinutes();
var h = date.getHours();
setTimeout(function () {
    $('#offer1').fadeOut('fast');
    $('#remainingTime').fadeOut('fast');
}, 8640000);
function Timer(duration, display) {
    var timer = duration, hours, minutes, seconds;
    setInterval(function () {
        hours = parseInt((timer / 3600) % 24, 10)
        minutes = parseInt((timer / 60) % 60, 10)
        seconds = parseInt(timer % 60, 10);
        hours = hours < 10 ? "0" + hours : hours;
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        display.text(parseInt(hours-h) + ":" + parseInt(minutes-m) + ":" + parseInt(seconds-s));
        --timer;
    }, 1000);
}
jQuery(function ($) {
    var twentyFourHours = 24 * 60 * 60;
    var display = $('#remainingTime');
    Timer(twentyFourHours, display);
});
var i =$("remainingTime").textContent;
console.log(i);
<div class="ml-2">Time Remaining&emsp;<span id="remainingTime">24:00:00</span></div>
<div id="offer1">asdf</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>

Here, I've made a timer which says how much time is left for 24 Hours.

But it's showing Hours, Minutes and seconds in negative value for seconds after a minute and negative value for minutes after an Hour.

I need the both div elements ("offer1" and "remainingTime") should fade out after 24 hours timer. By using the current Date and getTime() I should show the time remaining Here is the JSFiddle Link https://jsfiddle.net/Manoj07/d28khLmf/2/... Thanks for everyone who tried to help me. And here is the answer https://jsfiddle.net/Manoj07/1fyb4xv9/1/

jeevan kotian
  • 137
  • 2
  • 12

3 Answers3

2

Hello this code works for me

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>

<div class="ml-2">Time Remaining&emsp;<span id="remainingTime"></span></div>
<div id="offer1">asdf</div>
<script>
//  this code set time to 24 hrs
    var timer2 = "24:00:00";
    
    /* 
    if you want to get timer from localstorage
    var session_timer = localStorage.getItem('timer');
    if(session_timer){
        console.log('timer',session_timer);
        timer2 = session_timer;
    }
    */
    var interval = setInterval(function() {


        var timer = timer2.split(':');
        //by parsing integer, I avoid all extra string processing
        var hours = parseInt(timer[0], 10);
        var minutes = parseInt(timer[1], 10);
        var seconds = parseInt(timer[2], 10);
        --seconds;
        minutes = (seconds < 0) ? --minutes : minutes;
        hours = (minutes < 0) ? --hours : hours;
        if (hours < 0) clearInterval(interval);
        minutes = (minutes < 0) ? 59 : minutes;
        minutes = (minutes < 10) ? '0' + minutes : minutes;
        hours = (hours < 10) ?  '0' + hours : hours;
        if (minutes < 0) clearInterval(interval);
        seconds = (seconds < 0) ? 59 : seconds;
        seconds = (seconds < 10) ? '0' + seconds : seconds;
        minutes = (minutes < 10) ?  minutes : minutes;
        
        timer2 = hours+ ':' +minutes + ':' + seconds;    
        if(hours <= 0 && minutes == 0 && seconds == 0){
            // if you want to delete it on local storage
            // localStorage.removeItem('timer');
            console.log('finish')
            // fade out div element
            $( "#offer1" ).fadeOut( "slow", function() {
                // Animation complete.
            });
        }
        else{
            $('#remainingTime').html(timer2);
            // if you want to save it on local storage
            // localStorage.setItem('timer', timer2);
        }

    }, 1000);

        
    </script>
Sean Ret
  • 21
  • 1
1

See https://www.w3schools.com/howto/howto_js_countdown.asp for the code used to create a countdown timer

See how to get tomorrow's date: JavaScript, get date of the next day

// Set the date we're counting down to

const today = new Date()
const tomorrow = new Date(today)
tomorrow.setDate(tomorrow.getDate() + 1)
// Update the count down every 1 second
var x = setInterval(function() {

  // Get today's date and time
  var now = new Date().getTime();
    
  // Find the distance between now and the count down date
  var distance = tomorrow - now;
    
  // Time calculations for days, hours, minutes and seconds
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);
  hours = ("00" + hours).slice(-2);
  minutes = ("00" + minutes).slice(-2);
  seconds = ("00" + seconds).slice(-2);
  // Output the result in an element with id="demo"
  document.getElementById("demo").innerHTML = 'Time Remaining: '+hours + ":"
  + minutes + ":" + seconds;
    
  // If the count down is over, hide the countdown
  if (distance < 0) {
    $("#demo").hide();
  }
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
  text-align: center;
  font-size: 60px;
  margin-top: 0px;
}
</style>
</head>
<body>

<p id="demo"></p>
</body>
</html>
RainyRain
  • 305
  • 2
  • 10
  • the w3c countdown version seems to skip a second (or 2) sometimes, could try to add a version based on: https://stackoverflow.com/questions/20618355/the-simplest-possible-javascript-countdown-timer – RainyRain Mar 06 '20 at 08:35
  • Sir, But i need to get the remaining time what is left with respect to 24 Hours... Even after refreshing the page. It should get the current time and should show the difference. After that when the difference becomes to zero, the div should Hide – jeevan kotian Mar 06 '20 at 09:02
  • at what moment is the date determited from which the countdown will start? first time the user visits the page or a set date predefined before the first visit? – RainyRain Mar 06 '20 at 11:21
  • Countdown will start using the current time till the determined time... I mean, 8 Hours/12 Hours/24 Hours.when the countdown ends, the div elements should fade – jeevan kotian Mar 06 '20 at 12:11
  • @jeevankotian but the current time will be different every time you refresh the page, hence it will start at counting down again from 23:59:59 – RainyRain Mar 06 '20 at 13:11
1

createCountdown returns a countdown object with two methods: start and stop.

A countdown has a to date, an onTick callback, and a granularity.

The granularity is the frequency at which the onTick callback is invoked. So if you set a granularity of 1000ms, then the countdown will only tick once a second.

Once the difference between now and to is zero, the onComplete callback is called, and this hides the DOM node.

This solution uses requestAnimationFrame which will have a maximum resolution of about 16 milliseconds. Given that this is the maximum speed that the screen is updated, this is fine for our purposes.

const $ = document.querySelector.bind(document)
const now = Date.now
const raf = requestAnimationFrame
const caf = cancelAnimationFrame
const defaultText = '--:--:--:--'

const createCountdown = ({ to, onTick, onComplete = () => {}, granularityMs = 1, rafId = null }) => { 
    const start = (value = to - now(), grain = null, latestGrain = null) => {        
        const tick = () => {
            value = to - now()
            if(value <= 0) return onTick(0) && onComplete()
            latestGrain = Math.trunc(value / granularityMs)
            if (grain !== latestGrain) onTick(value)
            grain = latestGrain
            rafId = raf(tick)    
        }
        rafId = raf(tick)
    }
    const stop = () => caf(rafId)
    return { start, stop }    
}

const ho = (ms) => String(Math.trunc((ms/1000/60/60))).padStart(2, '0')
const mi = (ms) => String(Math.trunc((ms%(1000*60*60))/60000)).padStart(2, '0')
const se = (ms) => String(Math.trunc((ms%(1000*60))/1000)).padStart(2, '0')
const ms = (ms) => String(Math.trunc((ms%(1000)))).padStart(3, '0')

const onTick = (value) => $('#output').innerText = `${ho(value)}:${mi(value)}:${se(value)}:${ms(value)}`
const onComplete = () => $('#toFade').classList.add('hidden')
const to = Date.now() + (2 * 60 * 1000)
const { start, stop } = createCountdown({ to, onTick, onComplete })

$('button#start').addEventListener('click', start)
$('button#stop').addEventListener('click', () => (stop(), $('#output').innerText = defaultText))
div#toFade {
    opacity: 1;
    transition: opacity 5s linear 0s;
}

div#toFade.hidden {
    opacity: 0;
}
div {
    padding: 20px;
}
<button id="start">Start</button>
<button id="stop">Stop</button>
<div id="output">--:--:--:--</div>
<div id="toFade">This is the element to fade out.</div>
Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • Actually I needed Shopping Cart type of countdown sir... If the countdown ends then the element fades or vanishes. That type of – jeevan kotian Mar 06 '20 at 12:31