Как сделать Javascript обратный отсчет в течение 24 часов и исчезнуть элемент div после 24 часов? - PullRequest
1 голос
/ 06 марта 2020

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>

Здесь я сделал таймер, который сообщает, сколько времени осталось на 24 часа.

Но он показывает часы, минуты и секунды в отрицательном значении для секунд после минуты и отрицательное значение для минут после часа.

Мне нужны оба элемента div ("offer1" и "Остальное время" ") должен исчезнуть через 24 часа. Используя текущую Date и getTime (), я должен показать оставшееся время. Вот ссылка JSFiddle https://jsfiddle.net/Manoj07/d28khLmf/2/ ... Спасибо всем, кто пытался мне помочь. А вот и ответ https://jsfiddle.net/Manoj07/1fyb4xv9/1/

Ответы [ 3 ]

2 голосов
/ 06 марта 2020

Здравствуйте, у меня работает этот код

<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>
1 голос
/ 06 марта 2020

createCountdown возвращает объект обратного отсчета двумя методами: start и stop.

Обратный отсчет имеет дату to, обратный вызов onTick и granularity.

granularity - это частота, с которой вызывается обратный вызов onTick. Поэтому, если вы установите гранулярность 1000 мс, отсчет будет происходить только один раз в секунду.

Когда разница между now и to равна нулю, вызывается обратный вызов onComplete, и это скрывает узел DOM.

В этом решении используется requestAnimationFrame, максимальное разрешение которого составляет около 16 миллисекунд. Учитывая, что это максимальная скорость обновления экрана, это хорошо для наших целей.

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>
1 голос
/ 06 марта 2020

См. https://www.w3schools.com/howto/howto_js_countdown.asp для кода, используемого для создания таймера обратного отсчета

Узнайте, как получить завтрашнюю дату: JavaScript, получить дату следующего дня

// 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>
...