// ****** THE CLASS
var Loop=new Class({loopCount:0,isStopped:true,isLooping:false,loopMethod:$empty,setLoop:function(fn,delay){if(this.isLooping)this.stopLoop();this.loopMethod=fn;this.loopDelay=delay||3000;return this;},stopLoop:function(){this.isStopped=true;this.isLooping=false;$clear(this.periodical);return this;},startLoop:function(delay){if(this.isStopped){var delay=(delay)?delay:this.loopDelay;this.isStopped=false;this.isLooping=true;this.periodical=this.looper.periodical(delay,this);}
return this;},resetLoop:function(){this.loopCount=0;return this;},looper:function(){this.loopCount++;this.loopMethod(this.loopCount);return this;}});
// ****** IMPLEMENTING CLASS EXAMPLE
var LoopTest = new Class({
Implements: Loop,
initialize: function(log){
this.setLoop(this.update, 1000);
this.log = document.id(log);
},
update: function(count){
this.log.set('text',"Looped " + count + " times.");
}
});
// ****** USAGE
loop = new LoopTest('log');
$('start').addEvent('click',function(){
loop.startLoop();
});
$('stop').addEvent('click',function(){
loop.stopLoop();
});
$('reset').addEvent('click',function(){
loop.resetLoop();
});
$('change_delay').addEvent('click',function(){
loop.stopLoop()
.resetLoop()
.startLoop($('delay').value);
});
<h1>Loop.js Demo/Test</h1>
<h2 id="log">Waiting...</h2>
<div id="actions">
<h3>Public Methods</h3>
<p>
<button id="start">start</button> <button id="stop">stop</button> <button id="reset">reset</button>
</p>
<h3>State Tweaking</h3>
<p>
Delay: <input type="text" size="6" id="delay" value="1000" /> <button id="change_delay">Restart</button>
</div>