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

Jos*_*ley 31 html javascript timer

我想说一句话:

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

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

没有其他请求用简单的行说明"你下载将在x秒开始".我该怎么做?

Jam*_*ell 77

这将为您提供进度条

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

setInterval(makeAlert, 500);
Run Code Online (Sandbox Code Playgroud)
setInterval(function(){ alert("Popup window!"); }, 500);
Run Code Online (Sandbox Code Playgroud)

或者,这将创建文本倒计时.

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

  • 这是一个优雅的解决方案。为了使进度更顺利,您当然可以减少计时器(例如从1000到100)并增加时间(例如从10到100)。 (2认同)

Ted*_*ker 41

这是在文本中.

<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>
Run Code Online (Sandbox Code Playgroud)


tre*_*tar 6

使用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);
  });
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)