假设有这样一个动画功能需求:把一个div的宽度从100px变化到200px。写出来的代码可能是这样的:
<div id="test1" style="width: 100px; height: 100px; background: blue; color: white;"></div>
function animate1(element, endValue, duration) {
var startTime = new Date(),
startValue = parseInt(element.style.width),
step = 1;
var timerId = setInterval(function() {
var nextValue = parseInt(element.style.width) + step;
element.style.width = nextValue + 'px';
if (nextValue >= endValue) {
clearInterval(timerId);
// 显示动画耗时
element.innerHTML = new Date - startTime;
}
}, duration / (endValue - startValue) * step);
}
animate1(document.getElementById('test1'), 200, 1000);
原理是每隔一定时间增加1px,一直到200px为止。然而,动画结束后显示的耗时却不止1s(一般是1.5s左右)。究其原因,是因为setInterval并不能严格保证执行间隔。