在JavaScript中建立倒数计时器

news/2024/7/4 12:56:12

Countdown timers can serve many purposes. They can communicate to a user how long they’ve been doing something or how much time until some event happens, like the launch of your new website.

倒数计时器可以有多种用途。 他们可以与用户交流他们已经做了多长时间,或者直到某个事件(例如启动新网站)发生了多少时间。

In the sales and marketing context they can be used to create a sense of urgency to encourage the conversion. FOMO can be hard to beat, but building a countdown timer in pure JavaScript is easy!

在销售和市场环境中,它们可以被用来营造一种紧迫感,以鼓励这种转变。 FOMO很难被击败,但是用纯JavaScript构建倒数计时器很容易!

入门 (Getting Started)

Since we’re leveraging the power of JavaScript in it’s purest form, without any front-end libraries, there’s not a ton of bootstrapping that has to be done.

由于我们以最纯粹的形式利用JavaScript的强大功能,而没有任何前端库,因此无需进行大量引导。

All we need is a .html file with a <div> to inject the countdown timer’s output into and a <script> block that will house our code:

我们需要的是一个.html文件,其中带有<div>用于将倒数计时器的输出注入到其中,还有一个<script>块,用于容纳我们的代码:

<!DOCTYPE html>
<html>
  <body>
    <div id="countdown"></div>
    <script>
      // This is where our sweet timer code will go!
    </script>
  </body>
</html>

计算剩余时间 (Calculating the Time Remaining)

To calculate the time remaining, we need to find the difference between the current time and the time that our countdown timer will expire. One of the more notable times that we countdown to is New Year’s Day, so we’ll use the upcoming new year as our end time:

要计算剩余时间,我们需要找到当前时间与倒数计时器将要到期的时间之间的时差。 我们倒计时最值得注意的时间之一是元旦,因此我们将即将到来的新年作为结束时间:

const difference = +new Date("2020-01-01") - +new Date();

The + before the new Date is shorthand to tell JavaScript to cast the object as an integer, which gives us the object’s Unix time stamp represented as microseconds since the epoch.

new Date之前的+是表示JavaScript将对象强制转换为整数的简写形式,这使我们可以将对象的Unix时间戳记为自纪元以来的微秒。

格式化为天,小时,分钟和秒 (Formatting to Days, Hours, Minutes and Seconds)

Now that we know the total number of milliseconds until the countdown time expires, we need to convert the number of milliseconds to something a bit more friendly and human readable.

现在我们知道倒计时时间结束之前的总毫秒数,我们需要将毫秒数转换为更友好和更易读的内容。

We’re going to calculate the total number of hours, minutes and of course, seconds, by doing some math and using the modulus % operator:

我们将通过做一些数学运算并使用模数%运算符来计算小时,分钟和当然秒数的%

const parts = {
  days: Math.floor(difference / (1000 * 60 * 60 * 24)),
  hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
  minutes: Math.floor((difference / 1000 / 60) % 60),
  seconds: Math.floor((difference / 1000) % 60),
};

By rounding the numbers down, we’re able to drop the remainder to get the whole number value.

通过将数字四舍五入,我们可以舍去余数以获得整数值。

With an object full of the days, hours, minutes and seconds remaining, we can put things together into a string:

在剩余了几天,几小时,几分钟和几秒钟的对象的情况下,我们可以将所有内容放到一个字符串中:

const remaining = Object.keys(parts)
  .map((part) => {
    if (!parts[part]) return;
    return `${parts[part]} ${part}`;
  })
  .join(" ");

在页面上显示剩余时间 (Show the Time Remaining on the Page)

With the time parts assembled into a string, we can update our <div> to contain the value:

将时间部分组装成字符串后,我们可以更新<div>以包含值:

document.getElementById("countdown").innerHTML = remaining;

自动更新计时器 (Automatically Updating the Timer)

Thus far, we’ve calculated the time difference between the current time and the time that our countdown expires. We’ve broken that time into hours, minutes and seconds, and then updated the page with the time remaining.

到目前为止,我们已经计算出当前时间与倒数计时到期时间之间的时差。 我们将时间分为几小时,几分钟和几秒钟,然后用剩余时间更新了页面。

Then time stood still.

然后时间静止了。

Without additional logic to update the page periodically, the timer is stuck in place until the next time the page is loaded. Without an update, it’s hard to even describe it as a timer.

如果没有其他逻辑来定期更新页面,计时器将停留在原处,直到下次加载页面为止。 如果没有更新,甚至很难将其描述为计时器。

No big deal, we can easily create an interval to run every second (or 1000ms) and update the timer’s display:

没什么大不了的,我们可以轻松地创建一个间隔来运行每秒(或1000ms)并更新计时器的显示:

setInterval(() => {
  // This is where we'd recalculate the time remaining
}, 1000);

放在一起 (Putting it All Together)

Obviously that last example was a bit lacking. That’s because it’s time to put it all together into something usable, and even add in some additional niceties like updating the timer on page load (instead of waiting for the first run of the interval) and handling things when the timer has expired:

显然,最后一个例子有点缺乏。 这是因为是时候将所有这些放在一起,变成可用的东西了,甚至添加一些额外的功能,例如在页面加载时更新计时器(而不是等待间隔的第一次运行)以及在计时器到期时处理事情:

<!DOCTYPE html>
<html>
  <body>
    <div id="countdown"></div>
    <script>
      function countdownTimer() {
        const difference = +new Date("2020-01-01") - +new Date();
        let remaining = "Time's up!";

        if (difference > 0) {
          const parts = {
            days: Math.floor(difference / (1000 * 60 * 60 * 24)),
            hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
            minutes: Math.floor((difference / 1000 / 60) % 60),
            seconds: Math.floor((difference / 1000) % 60)
          };

          remaining = Object.keys(parts)
            .map(part => {
              if (!parts[part]) return;
              return `${parts[part]} ${part}`;
            })
            .join(" ");
        }

        document.getElementById("countdown").innerHTML = remaining;
      }

      countdownTimer();
      setInterval(countdownTimer, 1000);
    </script>
  </body>
</html>

You can check a working example of this code over on CodeSandbox.

您可以在CodeSandbox上查看此代码的有效示例。

翻译自: https://www.digitalocean.com/community/tutorials/js-building-countdown-timer


http://www.niftyadmin.cn/n/3649292.html

相关文章

RxJava的简单使用(一)

一测试订阅 Test public void testSubscribe() {//观察者&#xff0f;订阅者final Subscriber<String> subscriber new Subscriber<String>() {Overridepublic void onCompleted() {System.out.println("onCompleted in tread:" Thread.currentThread().…

[EntLib]关于SR.Strings的使用办法

编写者&#xff1a;郑昀UltraPower下载附件。安装String Resource Generator 1[1].2.5&#xff0c;运行SRGenerator.msi。然后给自己的工程中添加SR.strings文件&#xff0c;通过VS.NET在现有的.RESX或SR.strings文件设置Custom tool属性为&#xff1a;StringResourceTool或SRC…

android开源项目和框架

特效&#xff1a; http://www.theultimateandroidlibrary.com/ 常用效果&#xff1a; 1. https://github.com/novoda/ImageLoader 异步加载图片&#xff0c;缓存&#xff0c;生成缩略图&#xff0c; 基本上每个应用都会需要这个lib。 android-query框架 2. https://githu…

prisma 风格设置_Prisma中的身份验证-第1部分:设置

prisma 风格设置Unless if you’re using something like Firebase to handle your authentication, it can be a bit tricky to handle it in a way that is both secure and easy to manage. In this three-part series, we’re going to be going over how to setup your Gr…

RxBus-mvp模式下对Rxjav的封装(一)

一、首先定义一个Presenter接口&#xff1a;DataBusSubscriber 用来接受数据 public interface DataBusSubscriber {void onEvent(Object data); }二、定义一个RxBus的封装类 public class RxBus {public static final String TAG "RxBus";private static volatile…

VS 2005 Team Suite 轻松搞定白盒测试

注&#xff1a;此文的Word版本首次发表于&#xff1a; http://bbs.5etesting.com/viewthread.php?tid18&highlight%B0%D7%BA%D0%B2%E2%CA%D4 VS 2005 Team Suite轻松搞定白盒测试 &#xff08;此文已于《测试天地》杂志发表&#xff0c;如需转载&#xff0c;请与作者联系…

[推荐]dotNET中进程间同步/通信的经典框架

推荐一篇关于dotNET中常用的进程间同步或通信的框架文章&#xff1a;A C# Framework for Interprocess Synchronization and CommunicationBy Christoph Ruegg How to share resources and implement a rich message/data passing architecture between threads and processes …

Android 开发之RxJava 详解

我从去年开始使用 RxJava &#xff0c;到现在一年多了。今年加入了 Flipboard 后&#xff0c;看到 Flipboard 的 Android 项目也在使用 RxJava &#xff0c;并且使用的场景越来越多 。而最近这几个月&#xff0c;我也发现国内越来越多的人开始提及 RxJava 。有人说『RxJava 真是…