我写了一个自定义动画函数。它通常工作得很好,但是当我用不同的endCallbacks快速连续呼叫animate();
时,有时候回调会非常糟糕,导致在错误的时间进行错误的操作。如果多次调用同一函数的前一个实例,该如何停止?
问题是函数实例化多次并执行直到达到endValue。 currentValue被改变得非常快,以至于我只能看到我的html页面动画中的最后一个值。这隐藏了这种不需要的行为。
我第二次拨打animate();
时需要的是结束animate();
的第一个实例,并用新值和新回调触发一个新实例。同时我也想停止setTimeout()
函数,以确保没有错误的回调被触发。
window.onload = function(){
document.addEventListener('click', // some button
function(){
animate(1, 10);
}, false
);
}
function animate(startValue, endValue, callback, endCallback) {
var startValue = startValue,
currentValue = startValue,
endValue = endValue,
callback = callback,
timeout = null;
loopAnimation();
function loopAnimation(){
if (currentValue != endValue){
timeout = setTimeout(function(){
currentValue++;
// Callback executes some page manipulation code
if (typeof callback !== "undefined") callback(currentValue);
console.log(currentValue);
loopAnimation();
},500)
} else {
console.log("This callback triggers some specific changes in my page");
if (typeof endCallback !== "undefined") endCallback();
}
}
}
而是在控制台中看到的: 1,2,3, - 1,4,2,5 ...... 6,9,7,10,8,9,10
我'd喜欢看: 1,2,3, - 1,2 ... 7,8,9,10
但请记住,由于我在脚本中使用animate()
的方式,我可以绝对不要了解输入变量的名称或范围。这使我无法自己解决它。
你不能阻止一个功能从另一个执行。假设您正在使用jquery进行动画,您可以调用一个'.stop'方法来停止在该元素上运行的所有动画。 http://api.jquery.com/stop/ – lwalden 2015-03-08 21:35:58