Skip to content

Instantly share code, notes, and snippets.

@XiongLiding
Last active December 21, 2015 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XiongLiding/6304538 to your computer and use it in GitHub Desktop.
Save XiongLiding/6304538 to your computer and use it in GitHub Desktop.
从调用函数 timeTrigger 开始,在 time 指定的时间内,每隔一段时间 interval ,执行一次回调函数 trigger ,并且每次执行时,都带有当前进度。 可用于实现动画等效果。

使用示例:

timeTrigger(5000, 1000, function (percent) {
    console.log(percent);   
});

回调函数中的 percent 用来返回当前执行的进度,数值在 0 - 1 之间,执行结果如下:

0
0.2002
0.4002
0.6002
0.8004
1

其中 0 是第一次执行,1 是最后一次执行。

timeTrigger 存在一个预期的帧数 time / interval。

但实际上,由于 timeTrigger 是在每次执行完回调函数后,再设定下一次执行的时间,所以 interval 指定的是两次回调之间的间隔时间,并且由于执行过程中可能存在的阻塞,实际的间隔时间必然大于 interval 。

所以在实际使用中,会出现“跳帧”的现象:

timeTrigger(5, 1, function (percent) {
    console.log(percent);   
});

0
0.6
1

因此在使用的时候,千万不要依赖这个预期的帧数

function timeTrigger(time, interval, trigger) {
var stime = + new Date();
(function run() {
var ntime = + new Date();
var percent = (ntime - stime) / time;
if (percent > 1) percent = 1;
var falseToBreak = trigger(percent);
if (falseToBreak === false || percent == 1) return false;
setTimeout(function () {
run();
}, interval);
})();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment