创建一个简单JavaScript时钟

In most cases, showing the current time on a web page is redundant: any visitor already has a dozen ways to tell what time it is. However, building a simple clock is a useful way to learn the basics of “human readable” time in JavaScript, and, as we’ll see later, actually has several useful applications.

在大多数情况下,在网页上显示当前时间是多余的:任何访问者都已经有十多种方法来告知时间。 但是,构建简单的时钟是学习JavaScript中“人类可读”时间基础的有用方法,并且,正如我们稍后将看到的,它实际上具有几个有用的应用程序。

时钟基础 (Clock Basics)

Due to the feature’s redundancy, we shouldn’t be too worried about progressive enhancement, and can create the clock almost entirely in JavaScript. The only HTML we’ll add to the page is a <time> element:

由于功能的冗余性,我们不必太担心渐进式增强功能 ,它几乎可以完全使用JavaScript创建时钟。 我们将添加到页面的唯一HTML<time>元素

<time id="currtime"></time>

In our script we’ll create a reference to the element and the current time, borrowing from the Date() object. From that, we’ll derive the current hour, minute and seconds:

在脚本中,我们将引用Date() 对象创建对元素和当前时间的引用。 由此,我们将得出当前的小时,分​​钟和秒:

var currentTime = document.getElementById("currtime");
var timeNow = new Date();
var hh = timeNow.getHours();
var mm = timeNow.getMinutes();
var ss = timeNow.getSeconds();

Then, we’ll format and write that information into the element:

然后,我们将格式化该信息并将其写入元素:

var formattedTime = hh + " : " + mm + " : " + ss;
currentTime.innerHTML = formattedTime;

While you will get the current time added to the page using this code, you’ll also immediately see a problem: the time is presented only once, and never changes. In order to keep it updated, we must change currentTime repeatedly by wrapping it in a function:

使用此代码将当前时间添加到页面上后,您还将立即发现一个问题:时间仅显示一次,并且永远不会更改。 为了保持更新,我们必须通过将currentTime包装在函数中来反复更改currentTime

function updateTime(){
	var timeNow = new Date();
	var hh = timeNow.getHours();
	var mm = timeNow.getMinutes();
	var ss = timeNow.getSeconds();
	var formattedTime = hh + " : " + mm + " : " + ss;
    currentTime.innerHTML = formattedTime;
	setTimeout(updateTime, 1000);
}

Inside the function is a self-referential setTimeout timer, which will call on the function it is embedded within every second. Once that is in place, we only need call on the function from the outside once to get it started:

函数内部有一个自引用的setTimeout计时器,它将在每秒内调用它所嵌入的函数。 一旦就位,我们只需要从外部调用一次函数就可以启动它:

updateTime();

It’s important to understand that setTimeOut runs asynchronously with the rest of our JavaScript: any other code will continue to run after this point.

重要的是要了解setTimeOut与我们的其余JavaScript 异步运行:在此之后,任何其他代码将继续运行。

You might find that the clock’s seconds are slightly out of sync with the actual time: setTimeout isn’t guaranteed to run exactly every second, and its progress is unlikely to coincide precisely with the passing of actual time. You can address this by calling updateTime() more frequently inside of itself: every 500 milliseconds, or even every 100. Of course, calling the function with increased frequency also makes it more wasteful: at an interval of 100 milliseconds, you’ll be calling the function 10 times a second, but the time will only actually update once in that period.

您可能会发现时钟的秒数与实际时间略有不同步: setTimeout不能保证精确地每秒运行一次,并且其进度不太可能与实际时间完全一致。 您可以通过在其内部更频繁地调用updateTime()来解决此问题:每500毫秒,甚至每100毫秒一次。当然,增加频率调用该函数也会使它更加浪费:每隔100毫秒,您将每秒调用该函数10次,但该时间实际上只会在该时间段内更新一次。

整理演示文稿 (Cleaning Up The Presentation)

You’re likely to see one other problem: JavaScript reports getHours and the other time components as pure integers, starting at 0 for midnight and proceeding through 1, 2, etc. While this may work for some situations, in most cases we’d expect single-digit time measures to be preceded by a 0.

您可能getHours看到另一个问题:JavaScript将getHours和其他时间分量报告为纯整数,从0开始代表午夜,然后经过1、2等。虽然这在某些情况下可行,但在大多数情况下,期望单位时间度量以0开头。

While there’s many possible ways we could change this, I’ll take the safest route. Anything we have to do repeatedly should be handled by a helper function. I’ll call this one zeroPadder:

尽管有许多可能的方法可以更改此设置,但我将采取最安全的方法。 我们必须重复执行的任何操作都应由助手功能处理。 我将其称为一个zeroPadder

function zeroPadder(n) {
	return (parseInt(n, 10) < 10 ? "0" : "") + n; 
}

Inside updateTime(), the formattedTime line changes to call upon this new function for each component of time:

updateTime()内部, formattedTime行更改为针对每个时间部分调用此新函数:

formattedTime = zeroPadder(hh) + " : " + zeroPadder(mm) + " : " + zeroPadder(ss);

zeroPadder is written rather more tersely than the rest of the script, so it’s worthwhile taking a moment to look at it closely.

zeroPadder的编写要比脚本的其余部分简洁得多,因此值得花一点时间仔细研究一下。

First, zeroPadder is taking a variable: in the context of the function, this variable is called n. It’s also returning a new value for n, after a calculation. This new value is “inserted” into wherever it is called from.

首先, zeroPadder一个变量:在函数的上下文中,该变量称为n 。 计算后,它还会为n返回一个新值。 将此新值“插入”到调用它的位置。

The calculation uses parseInt, a function that takes a string and returns a number. While we’re passing zeroPadder a digit, parseInt won’t care: it converts it to a base 10 digit (base 10 due to the same number being used as a “radix” argument: the safest method). The result is then compared, to see if n is less than 10. If it is, "0" is prepended to n, otherwise, nothing changes.

计算使用parseInt ,该函数接受字符串并返回数字。 当我们向数字传递zeroPadderparseInt不会在乎:它将其转换为以10为基数的数字(由于使用相同的数字作为“基数”参数,所以以10为基数:最安全的方法)。 然后比较结果,以查看n是否小于10。如果为n ,则将“ 0”放在n ,否则,没有任何变化。

The function could be written to produce the exact same result in a far longer way:

可以编写该函数以更长的方式产生完全相同的结果:

function zeropadder(n) {
    n = parseInt(n, 10);
    if (n < 10) {
        n = "0" + n;
        }
    return n;
}

As a rule, smaller, more efficient code is always better, so long as it is understood.

通常,只要可以理解,较小,效率更高的代码总是更好。

24至12 (24-to-12)

Most people are more comfortable with 12-hour time, as opposed to JavaScript’s default 24-hour measurement. Fortunately, this is very easy to change. At the same time, we can tighten up our updateTime() function:

与JavaScript的默认24小时制相比,大多数人更习惯12小时制。 幸运的是,这很容易更改。 同时,我们可以加强我们的updateTime()函数:

function updateTime(){
	var timeNow = new Date();
	var hh = timeNow.getHours() % 12 || 12;
	var mm = timeNow.getMinutes();
	var ss = timeNow.getSeconds();
	var formatAMPM = (hh >= 12 ? "PM" : "AM");
    currentTime.innerHTML = hh + " : " + zeroPadder(mm) + " : " + zeroPadder(ss) + " " + formatAMPM;
	setTimeout(updateTime, 1000);
}

This also deserves an explanation:

这也值得解释:

  • The line that sets the formatAMPM variable is the simplest: it uses the previously introduced if-else shortcut syntax to see if hh is greater than or equal to 12. If it is, formatAMPM is set to a value of PM, otherwise, it is set to AM

    设置formatAMPM变量的formatAMPM行是最简单的:它使用前面介绍的if-else快捷方式语法来查看hh是否大于或等于12。如果是, formatAMPM设置为PM的值,否则为设置为AM

  • The line after that is a little tricker. First, the statement uses a remainder operator to find the value of hh after division by 12; the operation only ever returns integers. In this case, if hh is less than 12, it remains unchanged: 2 divided by 12 is less than 1, but if hh had a value of 16, the remainder after division by 12 would be 4, i.e. 4pm.

    此后的代码有点麻烦。 首先,语句使用求余运算符找到的值hh 12 后; 该操作只返回整数。 在这种情况下,如果hh小于12,则保持不变:2除以12小于1,但是如果hh的值为16,则除以12后的余数将为4,即下午4点。

  • The double pipe (||) operator means do the following if the previous operation resolves to false. In JavaScript, a numerical value of 0 is exactly equivalent to false, and can, in most instances, be used interchangeably for it. In other words, if the time is noon to 12:59:59, hh will have a value of 12. Dividing 12 by 12 gives a result a 0. As “0PM” can’t exist, the double pipe operator picks up on this result and corrects it to 12. Again, this could be written as a longer (and more complex) if statement.

    如果前一个操作解析为false双管道( || )运算符意味着执行以下操作 。 在JavaScript中,数值0完全等于false ,并且在大多数情况下可以互换使用。 换句话说,如果时间是中午12:59:59,则hh的值为12 。 将12除以12得到的结果为0。由于“ 0PM”不存在,因此双管道运算符会选择该结果并将其更正为12。同样,这可以写成更长(更复杂)的if语句。

Note that we’ve removed the formattedTime variable in favor of setting the innerHTML property of currentTime directly, without padding hh with a leading 0. Again, smaller and more efficient code is better: any variable we can drop, and thus not force JavaScript to store and track in memory, is a savings in performance.

请注意,我们删除了formattedTime变量,以便直接设置currentTimeinnerHTML属性,而不用前导0填充hh 。同样,更小,更有效的代码更好:我们可以删除任何变量,因此不强制JavaScript进行操作。在内存中存储和跟踪,可以节省性能。

进一步改进 (Further Improvements)

Obviously there’s a lot more that we could do here: at the very least, the <time> element needs a datetime attribute, and including the day in the display would be useful. We’ll look at doing just that, and much more, in the next article in this series.

显然,我们可以在这里做更多的事情:至少, <time>元素需要一个datetime属性,并且在显示中包括日期将很有用。 在本系列的下一篇文章中,我们将讨论这样做的更多内容。

翻译自: https://thenewcode.com/942/Create-A-Simple-JavaScript-Clock

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值