创建一个简单的 10 秒倒计时 [英] Create a simple 10 second countdown

查看:26
本文介绍了创建一个简单的 10 秒倒计时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一行写着:

您的下载将在(10、9、8 等,从页面加载开始)秒后开始.

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

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.

没有对简单的一行提出其他请求,即您的下载将在 x 秒后开始".我该怎么做?

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

推荐答案

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

JavaScript has built in to it a function called setInterval, which takes two arguments - a function, callback and an integer, timeout. When called, setInterval will call the function you give it every timeout milliseconds.

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

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

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

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

Once setInterval is called, it will run until you call clearInterval on 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.

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>

这篇关于创建一个简单的 10 秒倒计时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆