jeevan kotian
jeevan kotian

Reputation: 137

How to make Javascript countdown for 24 hours and fade out a div element after 24 Hours?

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/

Upvotes: 1

Views: 1464

Answers (3)

Ben Aston
Ben Aston

Reputation: 55769

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>

Upvotes: 1

Sean Ret
Sean Ret

Reputation: 21

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>

Upvotes: 2

RainyRain
RainyRain

Reputation: 305

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>

Upvotes: 1

Related Questions