@ yauhen-yakimovichによる回答よりもさらに一般的です:
使用Timeout
:
var repeat = (function () {
return function repeat(cbWhileNotTrue, period) {
/// <summary>Continuously repeats callback after a period has passed, until the callback triggers a stop by returning true. Note each repetition only fires after the callback has completed. Identifier returned is an object, prematurely stop like `timer = repeat(...); clearTimeout(timer.t);`</summary>
var timer = {}, fn = function () {
if (true === cbWhileNotTrue()) {
return clearTimeout(timer.t); // no more repeat
}
timer.t = setTimeout(fn, period || 1000);
};
fn(); // engage
return timer; // and expose stopper object
};
})();
使用Interval
:
var loop = (function () {
return function loop(cbWhileNotTrue, period) {
/// <summary>Continuously performs a callback once every period, until the callback triggers a stop by returning true. Note that regardless of how long the callback takes, it will be triggered once per period.</summary>
var timer = setInterval(function () {
if (true === cbWhileNotTrue()) clearInterval(timer);
}, period || 1000);
return timer; // expose stopper
};
})();
コメントに示されている 2 つの間のわずかな違い --repeat
メソッドはコールバックが実行された後にのみ繰り返されるため、「遅い」コールバックがある場合は、delay
ミリ秒ごとに実行されるのではなく、実行のたびに繰り返されますdelay
が、loop
メソッドはコールバックを起動します。毎delay
ミリ秒。途中で停止するにrepeat
は、返される識別子としてオブジェクトを使用するため、clearTimeout(timer.t)
代わりに使用します。
使用法:
@soufiane-hassou の回答と同じように:
var textScroller = document.getElementById('textScroller');
var text = 'Hello how are you?';
var c = 0;
var interval = repeat/* or loop */(function() {
textScroller.innerHTML += text[c];
c++;
return (c >= text.length);
}, 1000);
前述のように、時期尚早の停止は次のようになります。
/* if repeat */ clearTimeout(interval.t);
/* if loop */ clearInterval(interval);