Javascript 以天、小时、分钟、秒为单位的 Javasacript 倒数计时器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27182628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:50:01  来源:igfitidea点击:

Javasacript Countdown timer in Days, Hours, Minute, Seconds

javascriptphptimercountdowntimer

提问by Phoenix Ryan

I'm trying to create a time-based count down clock. It is not based upon current_dates. The initial time that will be pulled will be from a separate php file. This will be for a browser based-game. When someone clicks the button to initiate this script. it will check if certain requirements are met and if so then this script will initiate. Based upon the level of the object it will pull the initial timer for that proceeding level. Hope that makes sense. Anyhow I based the timer script off of the first code I provide.

我正在尝试创建一个基于时间的倒计时时钟。它不是基于 current_dates。将被拉取的初始时间将来自一个单独的 php 文件。这将适用于基于浏览器的游戏。当有人单击按钮启动此脚本时。它将检查是否满足某些要求,如果满足则此脚本将启动。根据对象的级别,它将拉动该进程级别的初始计时器。希望这是有道理的。无论如何,我是基于我提供的第一个代码来编写计时器脚本的。

This script only accounts for minutes and seconds. I modified it to include days and hours as well. Somewhere in the process I have messed up and the script doesn't even work at all. I'm also not quite sure if this would be the best method to calculate this. So, if you have a cleaner method at doing this please share. Thank you in advance.

这个脚本只占分钟和秒。我修改了它以包括天数和小时数。在这个过程中的某个地方我搞砸了,脚本甚至根本不起作用。我也不太确定这是否是计算此值的最佳方法。因此,如果您有更简洁的方法来执行此操作,请分享。先感谢您。

This script is based off of a minutes / seconds script I saw. Here's the original source:

该脚本基于我看到的分钟/秒脚本。这是原始来源:

<span id="countdown" class="timer"></span>
<script>
   var seconds = 60;
   function secondPassed() {
   var minutes = Math.round((seconds - 30)/60);
   var remainingSeconds = seconds % 60;
   if (remainingSeconds < 10) {
      remainingSeconds = "0" + remainingSeconds; 
   }
   document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
   if (seconds == 0) {
    clearInterval(countdownTimer);
    document.getElementById('countdown').innerHTML = "Buzz Buzz";
   } else {
    seconds--;
   }
   }
   var countdownTimer = setInterval('secondPassed()', 1000);
</script>

Here is the modified script that I am trying to include days, hours, minutes and seconds.

这是我试图包含天、小时、分钟和秒的修改后的脚本。

<span id="countdown"></span>
<script>
     var current_level = 93578;

     function timer() {

        var days = Math.round(current_level/86400);
        var remainingDays = Math.round(current_level - (days * 86400));

        if (days <= 0){
             days = current_level;
        }

        var hours = Math.round(remainingDays/3600);
        var remainingHours = Math.round(remainingDays - (hours * 3600));

        if (hours >= 24){
             hours = 23;
        }

        var minutes = Math.round(remainingHours/60);
        var remainingMinutes = Math.round(remainingHours - (minutes * 60));

        if (minutes >= 60) {
             minutes = 59;
        }

        var seconds = Math.round(remainingMinutes/60);

        document.getElementById('countdown').innerHTML = days + ":" + hours ":" + minutes + ":" + seconds;

        if (seconds == 0) {
             clearInterval(countdownTimer);
             document.getElementById('countdown').innerHTML = "Completed";
        }
     }
     var countdownTimer = setInterval('timer()', 1000);
</script>

回答by Phoenix Ryan

I finally got back to looking at this and re-wrote the code and this works like a charm.

我终于回过头来看看这个并重新编写了代码,这就像一个魅力。

var upgradeTime = 172801;
var seconds = upgradeTime;
function timer() {
  var days        = Math.floor(seconds/24/60/60);
  var hoursLeft   = Math.floor((seconds) - (days*86400));
  var hours       = Math.floor(hoursLeft/3600);
  var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
  var minutes     = Math.floor(minutesLeft/60);
  var remainingSeconds = seconds % 60;
  function pad(n) {
    return (n < 10 ? "0" + n : n);
  }
  document.getElementById('countdown').innerHTML = pad(days) + ":" + pad(hours) + ":" + pad(minutes) + ":" + pad(remainingSeconds);
  if (seconds == 0) {
    clearInterval(countdownTimer);
    document.getElementById('countdown').innerHTML = "Completed";
  } else {
    seconds--;
  }
}
var countdownTimer = setInterval('timer()', 1000);
<span id="countdown" class="timer"></span>

回答by Armand Karambasis

Personally I would use the jquery countdown timer integration. It is simple and having number of options to display in different formats. Since I am fairly new to JS as well, this was the easiest way I found to get a count/timer.

我个人会使用 jquery 倒数计时器集成。它很简单,并且有许多选项可以以不同的格式显示。由于我对 JS 也很陌生,这是我找到的最简单的获取计数/计时器的方法。

http://keith-wood.name/countdown.html

http://keith-wood.name/countdown.html

回答by vivek manavadariya

<span id="date_regist"></span>
<script type="text/javascript">
    <script src="http://rc.sefunsoed.org/assets/js/countdown/jquery.countdown.min.js"></script>
    var s = '2017/03/01 15:21:21';
      f = '2017/03/01 15:22:00';
format = '%-w <sup>week%!w</sup> ' + '%-d <sup>day%!d</sup> ' + '%H <sup>hr</sup> ' + '%M <sup>min</sup> ' + '%S <sup>sec</sup>';



    jQuery('#date_regist').countdown(s)  
        .on('update.countdown', function(event) {

    jQuery(this).html("<b>will be open </b>" + event.strftime(format));
  })
  .on('finish.countdown', function(event) {
    jQuery("#date_regist").remove()
    jQuery("body").append('<span id="date_regist"></span>')
    jQuery("#date_regist").countdown(f)
      .on('update.countdown', function(event) {

        jQuery(this).html("<b> is open for </b>" + event.strftime(format));
      })
      .on('finish.countdown', function(event) {
         jQuery('#rework').hide();
        //jQuery(this).html("<b> is closed.</b>");
      });
  });
</script>

回答by Simon Z

Here is my worked out and tested example, based on your code

这是我根据您的代码制定和测试的示例

<span id="countdown"></span>
<script>
     var current_level = 3002;

     function timer() {

        var days = Math.floor(current_level/86400);
        var remainingDays = current_level - (days * 86400);

        //if (days <= 0){
        //    days = current_level;
        //}

        var hours = Math.floor(remainingDays/3600);
        var remainingHours = remainingDays - (hours * 3600);

        //if (hours >= 24){
        //     hours = 23;
        //}

        var minutes = Math.floor(remainingHours/60);
        var remainingMinutes = remainingHours - (minutes * 60);

        //if (minutes >= 60) {
        //     minutes = 59;
        //}

        var seconds = remainingMinutes;

        document.getElementById('countdown').innerHTML = days + ":" + hours + ":" + minutes + ":" + seconds;

        //if (seconds == 0) {
        //    clearInterval(countdownTimer);
        //     document.getElementById('countdown').innerHTML = "Completed";
        //}

        current_level--;
     }
     var countdownTimer = setInterval(timer, 1000);
</script>

回答by Lokesh Ramchandani

    var seconds_inputs =  document.getElementsByClassName('deal_left_seconds');
    var total_timers = seconds_inputs.length;
    for ( var i = 0; i < total_timers; i++){
        var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_';
        var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
        var cal_seconds = seconds_inputs[i].getAttribute('value');

        eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';');
        eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';');
    }
    function timer() {
        for ( var i = 0; i < total_timers; i++) {
            var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');

            var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60);
            var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400));
            var hours = Math.floor(hoursLeft / 3600);
            var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
            var minutes = Math.floor(minutesLeft / 60);
            var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60;

            function pad(n) {
                return (n < 10 ? "0" + n : n);
            }
            document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days);
            document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours);
            document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes);
            document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds);

            if (eval('seconds_'+ seconds_prod_id) == 0) {
                clearInterval(countdownTimer);
                document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0);
            } else {
                var value = eval('seconds_'+seconds_prod_id);
                value--;
                eval('seconds_' + seconds_prod_id + '= ' + value + ';');
            }
        }
    }

    var countdownTimer = setInterval('timer()', 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" class="deal_left_seconds" data-value="1" value="10">
<div class="box-wrapper">
    <div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div>
</div>
<div class="box-wrapper">
    <div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div>
</div>
<div class="box-wrapper">
    <div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div>
</div>
<div class="box-wrapper hidden-md">
    <div class="seconds box"> <span class="key" id="deal_sec_1">00</span> <span class="value">SEC</span> </div>
</div>

回答by anulaibar

Thanks to OP Phoenix RyanI made the following React component using your solution. Many thanks!

感谢 OP Phoenix Ryan,我使用您的解决方案制作了以下 React 组件。非常感谢!

const Panel = ({label, n}) => (
  <div className="panel">
    <small>{label}</small>
    <span>{n < 10 ? "0" + n : n}</span>
  </div>
)

const App = () => {
  const [secondsLeft, setSecondsLeft] = React.useState(86403)

  React.useEffect(() => {
    const interval = setInterval(() => {
      if (secondsLeft == 0) {
        clearInterval(interval);
        console.log('Times up!')
      } else {
        setSecondsLeft(secondsLeft - 1)
      }
    }, 1000)
    return () => clearInterval(interval)
  })
  
  const days = Math.floor(secondsLeft/24/60/60);
  const hoursLeft = Math.floor((secondsLeft) - (days*86400));
  const hours = Math.floor(hoursLeft/3600);
  const minutesLeft = Math.floor((hoursLeft) - (hours*3600));
  const minutes = Math.floor(minutesLeft/60);
  const seconds = secondsLeft % 60;
    
  return (
    <div className="root">
      <Panel label="Days" n={days} />
      <Panel label="Hours" n={hours} />
      <Panel label="Minutes" n={minutes} />
      <Panel label="Seconds" n={seconds} />
    </div>
  )
}

ReactDOM.render(
  <App/>,
  document.getElementById('root')
)
.root {
  display: flex;
}

.panel {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 8px;
  color: #444;
}

.panel small {
  font-size: 9px;
  text-transform: uppercase;
  font-family: sans-serif;
}

.panel span {
  font-size: 3em;
  font-weight: bold;
  font-family: serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>