希望用requestAnimationFrame实现类似于 update(dt);的功能.
var distance = 0;
var dt;
function Frame() {
}
Frame.prototype.execFrame = function (callback, ...args) {
var arr = [];
var id = null;
var self = this;
this._clocking = true;
function step() {
var date = new Date().getTime();
arr.push(date);
if (arr.length > 2) arr.shift();
var timeUnit = arr.reduce(function (pre, cur) {
return cur - pre;
});
dt = timeUnit;
callback(...args);
id = requestAnimationFrame(step);
if (self._clocking == false) cancelAnimationFrame(id);
}
return step();
}
Frame.prototype.stopFrame = function (callback, ...args) {
this._clocking = false;
if ($.type(arguments[0]) != 'function' || !arguments.length) {
return;
} else {
callback(...args);
};
}
var f1 = new Frame();
f1.execFrame(function () {
distance += dt; //这个地方得到的结果很奇怪
console.log(distance);
});
奇怪的是当用 distance去实现dt的累加时,输出一串不知所云的数字:
1494840598806
1494840598821
1494840598837
1494840598854
1494840598872
1494840598887
可是如果不用累加,直接赋值,是正常的:
f1.execFrame(function () {
distance = dt; //如果不用累加又正常了
console.log(distance);
});
这是帧的毫秒数:
15
18
16
17
16
18
哪位大神知道为什么?