One possible approach:
var index = 0;
var text = 'Hello world!';
var textLength = text.length;
var elScreen = document.getElementById('screen');
(function type() {
var charToType = text.charAt(index);
if (charToType === ' ') {
charToType = '<br />';
}
elScreen.innerHTML += charToType;
index += 1;
if (index < textLength) {
setTimeout(type, 200);
}
})();
Demo. The key idea is very simple: when the character to be processed next is whitespace, it's replaced with <br />
.
Note two other changes here:
one can use function reference (instead of string) as setTimeout first param. In fact, one should use it this way.
unless there's a very big reason to do so, one should stop 'typing' that string when its end is reached - hence the
index < textLength
check.