Skip to content
Advertisement

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/

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement