I’d use a single string instead, and iterate over it asynchronously, creating new <span>
s and inserting them into the document instead of assigning to existing spans:
const delay = ms => new Promise(res => setTimeout(res, ms));
(async () => {
for (const char of 'SONY') {
await delay(1000);
document.body.insertAdjacentHTML('beforeend', ` <span>${char}</span>`);
}
})();
You can use the function window.setInterval
as follow which will execute the handler N seconds.
This approach is a bit different in order to make it “DRY”.
let chars = ["S", "O", "N", "Y"],
i = 0,
SPACE = " ",
id = setInterval(function() {
document.getElementById("word").innerHTML += chars[i++] + SPACE;
if (i === chars.length) clearInterval(id);
}, 1000);
<span id="word"></span>
You can have array of characters and then make a function to pass index and increment it with every setTimeout. When we reach last index, don’t call setTimeout.
If you need an callback when character loading is finished, you can add else condition in showCharacter
function.
var characters = ["S", "O", "N", "Y"];
function showCharacter(idx) {
document.getElementById("char").innerHTML += characters[idx];
if (idx != characters.length-1)
setTimeout(() => showCharacter(idx+1), 1000);
}
setTimeout(() => showCharacter(0), 1000); // First Call
<span id="char"></span>
Back to the old school…
function printSlowly(word, interval = 1000) {
function printCharacter(i = 0) {
console.log(word[i]) // or print to the DOM/whatever
if(++i >= word.length) return
setTimeout(printCharacter.bind(null, i), interval)
}
if(word.length) setTimeout(printCharacter, interval)
}
printSlowly(['s', 'o', 'n', 'y'])
…and with async functions:
async function printSlowly(word, interval = 1000) {
async function printCharacter(i = 0) {
await new Promise((resolve) => setTimeout(resolve, interval))
console.log(word[i]) // or print to the DOM/whatever
if(++i < word.length) await printCharacter(i)
}
await printCharacter()
}
printSlowly(['s', 'o', 'n', 'y'])
var firstChar = "S";
var secondChar = "O";
var thirdChar = "N";
var fourthChar = "Y";
setTimeout(function() {
document.getElementById("charOne").innerHTML += firstChar;
}, 1000);
setTimeout(function() {
document.getElementById("charTwo").innerHTML += secondChar;
}, 2000);
setTimeout(function() {
document.getElementById("charThree").innerHTML += thirdChar;
}, 3000);
setTimeout(function() {
document.getElementById("charFour").innerHTML += fourthChar;
}, 4000);
<span id="charOne"></span>
<span id="charTwo"></span>
<span id="charThree"></span>
<span id="charFour"></span>
The above code is done by me but not in good shape I just want to need a more flexible script to help me out here for getting the same result but with more reliable coding standards. OR should I use ARRAY in it.
Are you looking for a code review? Maybe should close this question and repost on