I'm trying to print one letter after another but this code just waits 100ms and then prints the value with no pauses. Any idea why this happens and how to fix it? Code:
for (let i = 0; i < welcText.length; i ) {
setTimeout(()=>{
welcome.innerText = welcText[i];
},100);
}
CodePudding user response:
Note that setTimeout
does not actually delay the running of the code that comes after; it just schedules for something to happen in the future. So all the letters are added at the same time, after 100 milliseconds.
The most straightforward way to fix it is to make each subsequent timeout wait a bit longer, by multiplying the delay with the index of the letter (i * 100
):
const welcome = document.getElementById('welcome');
const welcText = 'Welcome!';
for (let i = 0; i < welcText.length; i ) {
setTimeout(() => {
welcome.innerText = welcText[i];
}, i * 100);
}
<div id="welcome"></div>
CodePudding user response:
you can do it like this also
const welcText = 'Welcome!';
let i = 0;
const interval = setInterval(() => {
if (i >= welcText.length) {
clearInterval(interval);
} else {
document.getElementById('helloword').innerHTML = welcText[i];
i ;
}
}, 100);
<h1 id="helloword"></h1>
CodePudding user response:
This script executes a piece of code in a for loop every 100 ms:
var i = 1;
function myLoop() {
setTimeout(function() {
console.log(i);
i ;
if (i < 10) {
myLoop();
}
}, 100)
}
myLoop();