You might try something like this. Using setTimeout
is considered better than setInterval
because of the screwy ways that JS's event loop works. For the purposes of this example I'm passing in the word and div
where the word is meant to appear as parameters to the readWord
function.
The function sets up some variables and a named anonymous function (yes) in order for the setTimeout
to work. The readLetter
function immediately invokes when the function is first run, and then relies on the setTimeout
to continue. The important thing here is to check whether the letter count is less that the number of letters in the word.
var word = 'foshizzle';
var div = document.getElementById('div');
function readWord(word, el) {
var pos = 0;
var duration = 2500;
var text = '';
var readLetter = (function readLetter () {
if (pos < word.length) {
var letter = word.substr(pos, 1);
// show or say letter here
playSound('sounds/' + letter + '.mp3')
text += letter;
div.innerHTML = text;
pos++;
setTimeout(readLetter, duration);
}
})();
}
readWord(word, div);