You can do this with jQuery deferreds. In this case I had to use two recursive functions since you need flow control for both the iteration through the viewItems list as well as for kicking off setInterval()
to update #divAuto
for each character.
As an example of how promises are used here to add control, in autoType()
you get a promise returned from the new autoTypeUtil()
. When the promise is resolved within autoTypeUtil()
you call autoType()
again with the remaining list. This gives you flow control for the input items while still running asynchronously.
You may check out the fiddle for a working example.
function timeString(arr, timeFactor, deferred) {
if (arr.length === 0) { deferred.resolve(); }
var ch = arr.shift();
var deferredInternal = new $.Deferred();
var promise = deferredInternal.promise();
var delay = 100;
setTimeout(function () {
$('#divauto').append(ch);
deferredInternal.resolve("done");
}, delay * timeFactor)
promise.done(function() {
timeString(arr, timeFactor, deferred);
});
}
function autoTypeUtil(inputString, timeFactor) {
var deferredTimeString = new $.Deferred();
var deferredInternal = new $.Deferred();
var promiseTimeString = deferredTimeString.promise();
inputString = inputString.split('');
timeString(inputString, timeFactor, deferredTimeString);
promiseTimeString.then(function() {
deferredInternal.resolve()
});
return deferredInternal.promise();
}
function autoType(arr, timeFactor) {
if (arr.length === 0) { return; }
var promise = autoTypeUtil(arr.shift(), timeFactor);
promise.done(function() {
autoType(arr, timeFactor);
});
}
var viewItems = ["I", "love", "jQuery", "promises"];
autoType(viewItems, 1);