解决setInterval休眠问题 real-interval

码农软件 · 软件分类 · jQuery定时器插件 · 2020-01-01 06:57:16

软件介绍

real-interval

如果你用setTimeout或setInterval实现过网页倒计时功能,你就会发现:

当电脑或者APP休眠了一段时间后,倒计时会出现问题:它比正确的时间慢了。

real-interval能解决这个问题。

当休眠的电脑被唤醒后,它会计算出正确的运行时间,你的回调函数可以据此显示正确的剩余时间,或者判断何时应该停止倒计时。

安装

你可以通过npm安装real-interval

npm install real-interval

OR通过脚本引入它:

<script src="./build/interval.js"></script>

用法 1

在经过指定个数的时间间隔后停止

var timer = new Interval(function(pass){

    console.log(pass);

    // stop after 24 hours
    if(pass == 60*60*24){
        this.stop();
    };

}, 1000);

打印结果:

1
2
3
4
5
6
...
86400

这个例子中的 pass 是一个计数器, 表示当前经过了多少个1000毫秒。

用法 2

设定执行次数,自动停止

// automatic stop after 6 seconds
var timer = new Interval(function(pass){

    console.log(pass);

}, 1000, 6);

打印结果:

1
2
3
4
5
6

这个例子中的定时器会在6秒后自动停止。

用法 3

显示剩余时间

var timer = new Interval(function(pass, surplus){

    console.log('stop after ' + surplus + ' seconds');

}, 1000, 6);

打印结果:

stop after 5 seconds
stop after 4 seconds
stop after 3 seconds
stop after 2 seconds
stop after 1 seconds
stop after 0 seconds

这个例子会显示距离停止还有多少秒。

用法 4

立即执行

var timer = new Interval(function(pass, surplus){

    console.log('stop after ' + surplus + ' seconds');

}, 1000, 6, true);

打印结果:

stop after 6 seconds
stop after 5 seconds
stop after 4 seconds
stop after 3 seconds
stop after 2 seconds
stop after 1 seconds
stop after 0 seconds

这个例子与上个例子不同的地方在于, 回调函数会立即被调用, 而不是1秒之后。

本文地址:https://codercto.com/soft/d/22400.html

腾讯产品法

腾讯产品法

李立 / 浙江大学出版社 / 2018-1 / 49元

从QQ到微信,从《英雄联盟》到《王者荣耀》,腾讯公司凭借强大的产品力成为世界互联网企业中的佼佼者,其“小步快跑,试错迭代”的产品开发机制,“别让我思考”的极简主义理念,“变成白痴级用户”的用户驱动战略,都成为整个中国互联网行业竞相学习的典范。 本书向读者完整地呈现了腾讯产品设计的底层思路,阐述了设计者如何发现问题、定义问题、拆解问题的全过程,从“产品思维”出发,以需求、战略、产品设计开发与运......一起来看看 《腾讯产品法》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具