How to implement an accurate countdown timer with js
How to implement an accurate countdown timer with js
如何用 js 实现一个精确的倒计时器

原理剖析
web worker
js custom timer
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();
- 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的更多相关文章
- jQuery Countdown Timer 倒计时效果
这个一款简单的 jQuery 倒计时插件,用于显示剩余的天数,小时,分钟和秒.倒计时功能是非常有用的一个小功能,可以告诉用户多久以后您的网站将会发布或者关闭进行维护,还可以用于举办活动的开始和停止的倒 ...
- A WPF/MVVM Countdown Timer
Introduction This article describes the construction of a countdown timer application written in C# ...
- 深入出不来nodejs源码-timer模块(JS篇)
鸽了好久,最近沉迷游戏,继续写点什么吧,也不知道有没有人看. 其实这个node的源码也不知道该怎么写了,很多模块涉及的东西比较深,JS和C++两头看,中间被工作耽搁回来就一脸懵逼了,所以还是挑一些简单 ...
- Implement Custom Cache Dependencies in ASP.NET 1.x
Code download available at:CuttingEdge0407.exe(128 KB) Contents What's a Cache Dependency, Anyway? ...
- Java中定时器相关实现的介绍与对比之:Timer和TimerTask
Timer和TimerTask JDK自带,具体的定时任务由TimerTask指定,定时任务的执行调度由Timer设定.Timer和TimerTask均在包java.util里实现. 本文基于java ...
- 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 ...
- JUC回顾之-ScheduledThreadPoolExecutor底层实现原理和应用
项目中经常使用定时器,比如每隔一段时间清理下线过期的F码,或者应用timer定期查询MQ在数据库的配置,根据不同version实现配置的实时更新等等.但是timer是存在一些缺陷的,因为Timer在执 ...
- 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 ...
- Adaptive partitioning scheduler for multiprocessing system
A symmetric multiprocessing system includes multiple processing units and corresponding instances of ...
随机推荐
- 下面给出一个child-parent的表格,要求挖掘其中的父子辈关系,给出祖孙辈关系的表格。
package org.apache.hadoop.examples; import java.util.HashMap; import java.io.IOException; import jav ...
- 客户端必须在它发送到服务器的所有帧中添加掩码(Mask)
在WebSocket协议中,数据是通过一系列数据帧来进行传输的.为了避免由于网络中介(例如一些拦截代理)或者一些在第10.3节讨论的安全原因,客户端必须在它发送到服务器的所有帧中添加掩码(Mask)( ...
- 异步日志 Loguru
https://mp.weixin.qq.com/s/hy68s610B9GbL_wgwTn7nA 更优美的python日志管理库Loguru Asynchronous, Thread-safe, M ...
- (Oracle)常用的数据库函数
Trim: Trim() 函数的功能是去掉首尾空格. Eg: trim(to_char(level, '00')) Trunc: 1.TRUNC函数为指定元素而截去的日期值. trun ...
- 加密填补 填充 pad padding
RFC 1423 - Privacy Enhancement for Internet Electronic Mail: Part III: Algorithms, Modes, and Identi ...
- 理解 async/await以及对Generator的优势
async await 是用来解决异步的,async函数是Generator函数的语法糖使用关键字async来表示,在函数内部使用 await 来表示异步async函数返回一个 Promise 对象, ...
- 11.15 gryz校测(题解分析报告)
T1 心有灵犀 (cooperate) 题目大意 给你一个不超过 \(10^9\) 的数字 \(n\) 和一个交换次数上限 \(k\), 每次操作对这个 数字 \(n\) 的其中两位进行交换, 比如 ...
- Java——数据类型
数据类型分类 基本数据类型: 数值型: 整数类型(byte,short,int,long): 浮点类型(float,double): 字符型(char): 布尔值(boolean): 引用数据类型: ...
- Word 脚本 (自用)
打开开发工具 右击功能区->自定义功能区 勾选开发工具->确定 导入代码 开发工具选项卡->Visual Basic 右击Normal->插入->模块 粘贴代码-> ...
- Spring学习笔记2
一.什么是AOP 面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术.在不影响原来功能代码的基础上,使用动态代理加入自己需要的一些功能(比如权限的验证,事务的控制,日志的记录 ...