介绍
计时计时器可以服务于许多目的. 它们可以向用户传达他们做某事多久或多长时间,直到某些事件发生,例如推出新网站。
在本教程中,您将创建纯JavaScript的倒计时器。
前提条件
要完成本教程,您将需要以下内容:
要安装 Node,请按照本教程中描述的步骤(How To Install Node.js)(https://www.digitalocean.com/community/tutorial_collections/how-to-install-node-js) *您可以在本系列中找到的 JavaScript 编码的基本理解,名为 How to Code in JavaScript
步骤1 - 开始
由于你将以最纯粹的形式使用JavaScript,没有任何前端库,所以不需要做很多启动。
使用标准的 boilerplate HTML 启动代码创建一个 index.html
文件:
1[label index.html]
2<!DOCTYPE html>
3<html>
4 <body>
5
6 </body>
7</html>
在体
中添加一个div
。div
应该有一个id
设置为计数
:
1[label index.html]
2<!DOCTYPE html>
3<html>
4 <body>
5 <div id="countdown"></div>
6 </body>
7</html>
随后,JavaScript计时器的输出将被放置在这个<div>
内。下方包含你的<div>
标签,你的<script>
标签将包含你的JavaScript代码:
1[label index.html]
2<!DOCTYPE html>
3<html>
4 <body>
5 <div id="countdown"></div>
6 <script>
7
8 </script>
9 </body>
10</html>
有了您的HTML,您已经准备好继续使用JavaScript编码您的倒计时器,在下一步,您将计算剩余的时间。
步骤二:计算剩余时间
在计算剩余时间之前,创建一个名为countdownTimer
的函数:
1[label index.html]
2<!DOCTYPE html>
3<html>
4 <body>
5 <div id="countdown"></div>
6 <script>
7 function countdownTimer() {
8
9 }
10 </script>
11 </body>
12</html>
要计算剩余时间,您需要找到当前时间和您的倒计时器到期时间之间的差异。在倒计时器
函数中,创建一个名为差异
的恒定变量。在下面的代码片段中,差异
将设置为 2021 年新年日和当前日期之间的差异:
1[label index.html]
2function countdownTimer() {
3 const difference = +new Date("2021-01-01") - +new Date();
4}
新日期
之前的+
是指JavaScript将对象投放为整数,这为您提供了对象的Unix时刻印,以微秒为代表。
在差异
常数下方,创建一个名为剩余
的变量。
1[label index.html]
2function countdownTimer() {
3 const difference = +new Date("2020-01-01") - +new Date();
4 let remaining = "Time's up!";
5}
当您的时间结束,倒计时器结束时,将显示剩余
消息。
您的倒计时器上的剩余时间已设置,剩余时间(差异
)以毫秒计算,现在您需要将剩余时间格式化为天、小时、分钟和秒。
步骤 3 — 格式化为日期、小时、分钟和秒
随着数秒到倒计时期的总数计算,您需要将数毫秒转换为更易于人类读取的东西。
1[label index.html]
2function countdownTimer() {
3 const difference = +new Date("2020-01-01") - +new Date();
4 let remaining = "Time's up!";
5
6 if (difference > 0) {
7
8 }
9}
如果差异
大于0
(如果不是新年),将执行要遵循的代码。
现在你可以将毫秒转换为天,小时,分钟和秒. 要做到这一点,你需要做一些分割,倍增,并使用模块 %
操作员。
创建一个具有恒定的变量名称部分
的对象. 对象中的键应该是天
,小时
,分钟
和秒
,相应的值应匹配您将需要将毫秒转换为相应的时间单位的方程式。
1[label index.html]
2if (difference > 0) {
3 const parts = {
4 days: Math.floor(difference / (1000 * 60 * 60 * 24)),
5 hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
6 minutes: Math.floor((difference / 1000 / 60) % 60),
7 seconds: Math.floor((difference / 1000) % 60),
8 };
9}
使用Math.floor
函数将数字圆形下来,这样就可以放下剩余数以获得每个时间单位的整数值。
填充剩余的天、小时、分钟和秒的对象需要格式化为一个字符串。 要做到这一点,重新分配剩余
并将其设置为部分
中的数组键。
1[label index.html]
2if (difference > 0) {
3 const parts = {
4 days: Math.floor(difference / (1000 * 60 * 60 * 24)),
5 hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
6 minutes: Math.floor((difference / 1000 / 60) % 60),
7 seconds: Math.floor((difference / 1000) % 60),
8 };
9
10 remaining = Object.keys(parts)
11}
现在设置剩余
等于部分
中的一个数组键。由于剩余
现在是一个数组,您可以使用.map()
方法。
1[label index.html]
2
3if (difference > 0) {
4 const parts = {
5 days: Math.floor(difference / (1000 * 60 * 60 * 24)),
6 hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
7 minutes: Math.floor((difference / 1000 / 60) % 60),
8 seconds: Math.floor((difference / 1000) % 60),
9 };
10
11 remaining = Object.keys(parts).map(part => {
12
13 })
14}
您要将每个项目转换为一个字符串. 每个时间单位应遵循这个格式: X 天
。 part
匹配时间单位. 要抓住实际数字,您需要使用parts
对象的号。 创建一个if
声明,以检查对应时间单位是否没有数字。 如果没有数字,请添加返回声明:
1[label index.html]
2remaining = Object.keys(parts).map(part => {
3 if (!parts[part]) return;
4})
如果没有相应的数字,则 .map()
方法将移动到下一个时间单位,然后再次检查。
如果有一个数字,请返回该数字和时间单位,请记住,它应该遵循X天
格式:
1[label index.html]
2remaining = Object.keys(parts).map(part => {
3 if (!parts[part]) return;
4 return `${parts[part]} ${part}`;
5})
「${parts[part]」將返回數字,而「${part}」將返回時間單位。現在,「resining」是數日、小時、分鐘和秒的數組。 這個數組必須是一個字符串。 在「resining」中的每個項目都應該分開一個空間。 使用「.join(" ")」方法來完成這一點:
1[label index.html]
2remaining = Object.keys(parts).map(part => {
3 return `${parts[part]} ${part}`;
4}).join(" ");
现在,您的countdownTimer()
函数将看起来如下:
1[label index.html]
2function countdownTimer() {
3 const difference = +new Date("2020-01-01") - +new Date();
4 let remaining = "Time's up!";
5
6 if (difference > 0) {
7 const parts = {
8 days: Math.floor(difference / (1000 * 60 * 60 * 24)),
9 hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
10 minutes: Math.floor((difference / 1000 / 60) % 60),
11 seconds: Math.floor((difference / 1000) % 60),
12 };
13 remaining = Object.keys(parts).map(part => {
14 return `${parts[part]} ${part}`;
15 }).join(" ");
16 }
17}
剩余的时间现在被格式化为可理解的字符串和时间单位,但是剩余的时间还不会显示在您的页面上。
步骤 4 – 显示页面上剩余的时间
随着时间部分组合成一个字符串,您可以更新您的<div>
,以包含该值。
在您的countdownTimer()
函数中,并在您的if
语句下方,使用getElementById
DOM选择器来引用div>
和countdown
的id
:
1[label index.html]
2function countdownTimer() {
3 const difference = +new Date("2020-01-01") - +new Date();
4 let remaining = "Time's up!";
5
6 if (difference > 0) {
7 const parts = {
8 days: Math.floor(difference / (1000 * 60 * 60 * 24)),
9 hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
10 minutes: Math.floor((difference / 1000 / 60) % 60),
11 seconds: Math.floor((difference / 1000) % 60),
12 };
13 remaining = Object.keys(parts).map(part => {
14 return `${parts[part]} ${part}`;
15 }).join(" ");
16 }
17
18 document.getElementById("countdown")
19}
若要更改此「
1[label index.html]
2document.getElementById("countdown").innerHTML = remaining;
现在,countdownTimer()
函数已经完成,请调用该函数运行:
1[label index.html]
2function countdownTimer() {
3 const difference = +new Date("2020-01-01") - +new Date();
4 let remaining = "Time's up!";
5
6 if (difference > 0) {
7 const parts = {
8 days: Math.floor(difference / (1000 * 60 * 60 * 24)),
9 hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
10 minutes: Math.floor((difference / 1000 / 60) % 60),
11 seconds: Math.floor((difference / 1000) % 60),
12 };
13 remaining = Object.keys(parts).map(part => {
14 return `${parts[part]} ${part}`;
15 }).join(" ");
16 }
17
18 document.getElementById("countdown").innerHTML = remaining;
19}
20
21countDownTimer();
现在你的计时时间已经准备好在你的HTML页面上显示。你可能会注意到时间没有更新。还有更多的代码可以添加,以确保计时时间器自动更新。
步骤 5 – 自动更新时间表
到目前为止,您已经计算了当前时间和倒计时期的时间之间的时间差异. 您已经将该时间划分为小时、分钟和秒,然后将页面更新为剩余时间。
没有额外的逻辑来定期更新页面,计时器会停留到下次页面加载为止。
使用setInterval
方法并将countdownTimer
和1000
作为其两个参数输入:
1[label index.html]
2countdownTimer();
3setInterval(countdownTimer, 1000);
现在,计时计时器
将每秒运行(或1000ms),并更新计时器的显示屏。
结论
在本教程中,您使用纯JavaScript创建了计时计时器,您使用了诸如.map()
和setInterval
等方法,如果您想对这些方法获得更深入的了解,则 How To Use .map()
to Iterate Through Array Items in JavaScript和 Scheduling Tasks in JavaScript Using setTimeout
and setInterval
可以有所帮助。
有了这个项目完成,一个很好的下一步是添加 React 到混合物. 这个 如何使用 React Hooks 创建计时器教程是一个很好的开始。