假设你想一个无限循环,并在一个对象的范围内工作...
...
animation : ["first","second","third","etc"],
frameDelay : 400,
frameIndex : 0,
animationTimer : null,
start : function() {
// remember the scope of this object.
var handle = this;
// start the animation.
handle._nextFrame(handle);
},
_nextFrame : function(handle) {
// TODO: use frameIndex to render stuff... such as:
var animation = handle.animation[frameIndex];
$('body').html('<p>'+animation+'</p>');
// count your frames. You might add stuff to the sequence elsewhere.
var numFrames = handle.animation.length;
frameIndex = frameIndex < numFrames ? frameIndex++ : 0;
handle.animationTimer = window.setTimeout(function() {
handle._nextFrame(handle); }, handle.frameDelay);
},
_destroy : function() {
var handle = this;
clearTimeout(handle.animationTimer);
}...
备注: 我使用老式的方法强调界面上的私人功能。你不必以这种方式命名你的变量,而且它们不是私有的。
你会注意到我把“this”存储到“handle”中。你不能总是依赖这个范围,比如从一个事件泡泡调用一个对象函数,从一个公共接口调用它,或者在内部引用一个函数到对象。所以我只是把它作为一个惯例。
把这段代码放到你的对象中,调用'start'函数,它应该继续做它的事情,直到你离开页面。此外,请务必清理递归超时,而不是在页面刷新或页面导航时出现错误。
什么不起作用? – locrizak
它没有做任何事情,我希望它切换字体,你看看jsfiddle吗? –
它不切换字体,因为用户没有字体(我是其中之一)。它为我开关颜色 – locrizak