Javascript 创建一个简单的 10 秒倒计时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31106189/
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-23 06:14:09  来源:igfitidea点击:

Create a simple 10 second countdown

javascripthtmltimer

提问by Joseph Christian Hefley

I would like a line that says:

我想要一行写着:

Your download will begin in (10, 9, 8, etc. Beginning on page load) seconds.

Your download will begin in (10, 9, 8, etc. Beginning on page load) seconds.

I already have the 10 second download text set up, and I have looked at other stackoverflow posts. They all include CSS, and Jquery. I would like just a Javascript/HTML timer.

我已经设置了 10 秒的下载文本,并且查看了其他 stackoverflow 帖子。它们都包括 CSS 和 Jquery。我只想要一个 Javascript/HTML 计时器。

No other requests have been made for a simple line stating "You're download will begin in x seconds". How would I do this?

没有对简单的一行提出其他请求,说明“您的下载将在 x 秒后开始”。我该怎么做?

回答by James McDowell

JavaScript has built in to it a function called setInterval, which takes two arguments - a function, callbackand an integer, timeout. When called, setIntervalwill call the function you give it every timeoutmilliseconds.

JavaScript 内置了一个名为 的函数setInterval,它接受两个参数 - 一个函数callback和一个整数,timeout。当被调用时,setInterval将每timeout毫秒调用一次你给它的函数。

For example, if you wanted to make an alert window every 500 milliseconds, you could do something like this.

例如,如果您想每 500 毫秒创建一个警报窗口,您可以这样做。

function makeAlert(){ 
    alert("Popup window!");
};

setInterval(makeAlert, 500);

However, you don't have to name your function or declare it separately. Instead, you could define your function inline, like this.

但是,您不必命名您的函数或单独声明它。相反,您可以像这样内联定义您的函数。

setInterval(function(){ alert("Popup window!"); }, 500);

Once setIntervalis called, it will run until you call clearIntervalon the return value. This means that the previous example would just run infinitely. We can put all of this information together to make a progress bar that will update every second and after 10 seconds, stop updating.

一旦setInterval被调用,它将一直运行,直到您调用clearInterval返回值。这意味着前面的示例将无限运行。我们可以将所有这些信息放在一起,制作一个进度条,每秒更新一次,10 秒后停止更新。

var timeleft = 10;
var downloadTimer = setInterval(function(){
  if(timeleft <= 0){
    clearInterval(downloadTimer);
  }
  document.getElementById("progressBar").value = 10 - timeleft;
  timeleft -= 1;
}, 1000);
<progress value="0" max="10" id="progressBar"></progress>

Alternatively, this will create a text countdown.

或者,这将创建一个文本倒计时。

var timeleft = 10;
var downloadTimer = setInterval(function(){
  if(timeleft <= 0){
    clearInterval(downloadTimer);
    document.getElementById("countdown").innerHTML = "Finished";
  } else {
    document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
  }
  timeleft -= 1;
}, 1000);
<div id="countdown"></div>

回答by Teddy Koker

This does it in text.

这是在文本中完成的。

<p> The download will begin in <span id="countdowntimer">10 </span> Seconds</p>

<script type="text/javascript">
    var timeleft = 10;
    var downloadTimer = setInterval(function(){
    timeleft--;
    document.getElementById("countdowntimer").textContent = timeleft;
    if(timeleft <= 0)
        clearInterval(downloadTimer);
    },1000);
</script>

回答by Brandon Trecki

A solution using Promises, includes both progress bar & text countdown.

使用 Promises 的解决方案包括进度条和文本倒计时。

ProgressCountdown(10, 'pageBeginCountdown', 'pageBeginCountdownText').then(value => alert(`Page has started: ${value}.`));

function ProgressCountdown(timeleft, bar, text) {
  return new Promise((resolve, reject) => {
    var countdownTimer = setInterval(() => {
      timeleft--;

      document.getElementById(bar).value = timeleft;
      document.getElementById(text).textContent = timeleft;

      if (timeleft <= 0) {
        clearInterval(countdownTimer);
        resolve(true);
      }
    }, 1000);
  });
}
<div class="row begin-countdown">
  <div class="col-md-12 text-center">
    <progress value="10" max="10" id="pageBeginCountdown"></progress>
    <p> Begining in <span id="pageBeginCountdownText">10 </span> seconds</p>
  </div>
</div>

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