Javascript倒计时器,以天,小时,分钟,秒为单位

时间:2014-11-28 05:47:11

标签: javascript php timer countdowntimer

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

此脚本仅占用分钟和秒。我将其修改为包括日期和小时。在这个过程的某个地方,我搞砸了,剧本根本不起作用。我也不太确定这是否是计算这个的最佳方法。所以,如果你有一个更干净的方法,请分享。提前谢谢。

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

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

以下是我尝试包含天,小时,分钟和秒的修改后的脚本。

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

7 个答案:

答案 0 :(得分:21)

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

&#13;
&#13;
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);
&#13;
<span id="countdown" class="timer"></span>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

您可以使用此js有效管理计时器。

http://countdownjs.org/

答案 2 :(得分:1)

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

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

答案 3 :(得分:1)

此代码将帮助您处理在单个页面上处理多个计时器的问题

    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>

答案 4 :(得分:0)

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

答案 5 :(得分:0)

这是我根据您的代码

制定并测试的示例
<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>

答案 6 :(得分:0)

感谢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>