How to implement an accurate countdown timer with js

如何用 js 实现一个精确的倒计时器

原理剖析

  1. web worker

  2. js custom timer

  3. setTimeout / setInterval async bug (宏任务)


"use strict"; /**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-07-0
* @modified
*
* @description 使用 JavaScript 实现精确的 setTimeout 和 setInterval
* @difficulty Easy Medium Hard
* @complexity O(n)
* @augments
* @example
* @link
* @solutions
*
*/ const log = console.log; // 同步: 使用 js 实现精确的 setTimeout
function setTimeoutPreciseSimulator(callback, time = 0) {
const begin = new Date().getTime();
while (true) {
const end = new Date().getTime();
if(end - begin >= time) {
log(`end - begin`, end - begin);
callback();
break;
}
}
} // 同步: 使用 js 实现精确的 setInterval
function setIntervalPreciseSimulator(callback, time = 0, count = 10) {
function interval(callback, time) {
const begin = new Date().getTime();
while (true) {
const end = new Date().getTime();
if(end - begin >= time) {
log(`end - begin`, end - begin);
callback();
break;
}
}
if(count) {
log(`\ncount =`, count);
count--;
interval(callback, time);
}
}
// init
interval(callback, time);
}

solution

"use strict";

/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-07-24
* @modified
*
* @description 如何用 js 实现一个精确的倒计时器
* @difficulty Easy Medium Hard
* @complexity O(n)
* @augments
* @example
* @link https://gaohaoyang.github.io/2016/11/25/how-to-write-a-count-down/
* @solutions
*
*/ const log = console.log; // 同步: 使用 js 实现精确的 setTimeout
function setTimeoutPreciseSimulator(callback, time = 0) {
const begin = new Date().getTime();
while (true) {
const end = new Date().getTime();
if(end - begin >= time) {
// log(`end - begin`, end - begin);
callback();
break;
}
}
} // 同步: 使用 js 实现精确的 setInterval
function setIntervalPreciseSimulator(callback, time = 0) {
function interval(callback, time) {
const begin = new Date().getTime();
while (true) {
const end = new Date().getTime();
if(end - begin >= time) {
// log(`end - begin`, end - begin);
callback();
break;
}
}
if(!hasFished) {
interval(callback, time);
}
}
// init
interval(callback, time);
} // 首次进入页面获取 server 的时间和 server 剩余的时间 / server 结束的时间
const autoCalculatorRemainTime = (serverTime, endTime) => {
// const now = Date.parse(new Date());
// const now = new Date().getTime();
let total = endTime - serverTime;// ms
while(total) {
const seconds = Math.floor((total / 1000) % 60);
const minutes = Math.floor((total / (1000 * 60)) % 60);
const hours = Math.floor((total / (1000 * 60 * 60)) % 24);
const days = Math.floor(total / (1000 * 60 * 60 * 24));
total -= 1000;
setTimeoutPreciseSimulator(() => {
log(`days hours minutes seconds =\n`, `${days}天-${hours}时-${minutes}分-${seconds}秒`);
}, 1000);
// log(`days hours minutes seconds =\n`, `${days}天-${hours}时-${minutes}分-${seconds}秒`);
}
log(` 倒计时结束!`);
// return {
// total,
// days,
// hours,
// minutes,
// seconds,
// };
} // DOM demo new Date(`2020-07-30 11:00:00`).getTime();
// 1596078000000
new Date(`2020-07-30 11:00:01`).getTime();
// 1596078001000
// 3分钟后, 1s === 1000ms, 3 * 60 * 1000 === 180000ms
new Date(`2020-07-30 11:00:00`).getTime() + 3 * 60 * 1000;
// 1596078180000 const serverTime = new Date().getTime();
// 3分钟后
const endTime = new Date(serverTime + 3 * 60 * 1000).getTime(); autoCalculatorRemainTime(serverTime, endTime); // let hasFished = false;
// setIntervalPreciseSimulator();

  1. new Date() 获取时间差,计算
/**
* 获取剩余时间
* @param {Number} endTime 截止时间
* @param {Number} deviceTime 设备时间
* @param {Number} serverTime 服务端时间
* @return {Object} 剩余时间对象
*/
const getRemainTime = (endTime, deviceTime, serverTime) => {
let t = endTime - Date.parse(new Date()) - serverTime + deviceTime;
let seconds = Math.floor((t / 1000) % 60);
let minutes = Math.floor((t / 1000 / 60) % 60);
let hours = Math.floor((t / (1000 * 60 * 60)) % 24);
let days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds,
};
}

demo

https://www.online-stopwatch.com/chinese/

https://www.online-stopwatch.com/chinese/full-screen-stopwatch.php

refs



xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


How to implement an accurate countdown timer with js的更多相关文章

  1. jQuery Countdown Timer 倒计时效果

    这个一款简单的 jQuery 倒计时插件,用于显示剩余的天数,小时,分钟和秒.倒计时功能是非常有用的一个小功能,可以告诉用户多久以后您的网站将会发布或者关闭进行维护,还可以用于举办活动的开始和停止的倒 ...

  2. A WPF/MVVM Countdown Timer

    Introduction This article describes the construction of a countdown timer application written in C# ...

  3. 深入出不来nodejs源码-timer模块(JS篇)

    鸽了好久,最近沉迷游戏,继续写点什么吧,也不知道有没有人看. 其实这个node的源码也不知道该怎么写了,很多模块涉及的东西比较深,JS和C++两头看,中间被工作耽搁回来就一脸懵逼了,所以还是挑一些简单 ...

  4. Implement Custom Cache Dependencies in ASP.NET 1.x

    Code download available at:CuttingEdge0407.exe(128 KB)   Contents What's a Cache Dependency, Anyway? ...

  5. Java中定时器相关实现的介绍与对比之:Timer和TimerTask

    Timer和TimerTask JDK自带,具体的定时任务由TimerTask指定,定时任务的执行调度由Timer设定.Timer和TimerTask均在包java.util里实现. 本文基于java ...

  6. System and method for controlling switching between VMM and VM using enabling value of VMM timer indicator and VMM timer value having a specified time

    In one embodiment, a method includes transitioning control to a virtual machine (VM) from a virtual ...

  7. JUC回顾之-ScheduledThreadPoolExecutor底层实现原理和应用

    项目中经常使用定时器,比如每隔一段时间清理下线过期的F码,或者应用timer定期查询MQ在数据库的配置,根据不同version实现配置的实时更新等等.但是timer是存在一些缺陷的,因为Timer在执 ...

  8. Adaptively handling remote atomic execution based upon contention prediction

    In one embodiment, a method includes receiving an instruction for decoding in a processor core and d ...

  9. Adaptive partitioning scheduler for multiprocessing system

    A symmetric multiprocessing system includes multiple processing units and corresponding instances of ...

随机推荐

  1. CSGO项目

    #include <Windows.h> #include <sstream> #include <iostream> #include <math.h> ...

  2. 获取当前文件路径 import 原理 一般把模块组成的集合称为包(package)

    获取当前文件路径 testpath.py import sysprint(sys.path) [root@d mapReduceLog]# python testpath.py['/data/mapR ...

  3. LIS的优化

    二分优化 在求一个最长不上升自序列中,显然其结尾元素越小,越有利于接其他元素,对答案的贡献也就可能会更高 那么我们可以用low[i]去存长度为i的LIS结尾元素的最小值 因此我们只要维护low数组 对 ...

  4. loj10007线段

    题目描述 数轴上有 n 条线段,选取其中 k 条线段使得这 k 条线段两两没有重合部分,问 k 最大为多少. 输入格式 第一行为一个正整数 n: 在接下来的 n 行中,每行有 2 个数 a_i,b_i ...

  5. 五:SpringBoot-多个拦截器配置和使用场景

    SpringBoot-多个拦截器配置和使用场景 1.拦截器简介 1.1 拦截器中应用 2.拦截器用法 2.1 编写两个拦截器 2.1.1 OneInterceptor 拦截器 2.1.2 TwoInt ...

  6. Linux命令之Crontab定时任务,利用Crontab定时执行spark任务

    Linux命令之Crontab定时任务,利用Crontab定时执行spark任务 一.Linux命令之Crontab定时任务 1.1 常见Crontab任务 1.1.1 安装crontab 1.1.2 ...

  7. C++基本之--静态成员函数和静态成员变量

    #include <iostream> using namespace std; class Internet { public: Internet(char *name,char *ad ...

  8. (3)UNIX/Linux系统结构

    UNIX/Linux 系统可以粗糙地抽象为 3 个层次,如图所示.底层是 UNIX/Linux 操作系统,即系统内核(Kernel):中间层是Shell层,即命令解释层:高层则是应用层. 1) 内核层 ...

  9. DedeCMS程序使用拼音首字母做栏目名称的方法

    Dedecms织梦程序默认使用拼音为保存目录的时候使用的是中文全拼,当遇到栏目名称比较长的时候目录名称看起来有点冗长,这时候大多数站长喜欢使用拼音首字母作为栏目的保存目录,那么就需要修改 dede/c ...

  10. Array循环for、for in、for of、forEach各间优劣

    JavaScript中有多种循环Array的方式,你是否常常分不清他们的细微差别,和适用场景.本文将详细梳理各间的优缺点,整理成表以便对比. 循环 可访问element 可访问index 可迭代pro ...