Reputation: 302
I'm trying to make a function to write some text character by character, with some delay, I've expected this would work but it doesn't, after 1000ms the word is written completely, if anyone can help me to fix this or show me a better way to do this it would be really great, here is my code:
const container = document.getElementById('typer')
function typer(text) {
for(let i = 0; i <= text.length; i++) {
setInterval(() => {
container.innerHTML = text.substr(0, i)
}, 1000)
}
}
let x = "hello"
typer(x)
Upvotes: 1
Views: 536
Reputation: 961
setInterval is already act as a loop. So you can do as simple as below
const container = document.getElementById('typer');
function typer(text) {
let counter = 0, my_delay = setInterval(() => {
if(counter<text.length) container.innerHTML += text[counter++];
else clearInterval(my_delay);
}, 1000);
}
typer("hello");
<p id="typer"></p>
Upvotes: 1
Reputation: 461
actually you are doing it partially right but when the for loop runs it set all the setintervals for 1000 millisecond so all of them fired after 1 second that's why we always see hello
what i am done is i put fe for loop inside setinterval and added a setTimeout and each timeout will fire only after 500 millisecond after than the previous one,
the const sum = (text.length * (text.length +1)) / 2;
is used to find sum of all i
values which is used inside the for loop then only we will be able to fire setInterval only after the hello completed hope this helps you
but actually there is a simple css way is there you must try that. https://css-tricks.com/snippets/css/typewriter-effect/
const container = document.getElementById('typer')
function typer(text) {
const sum = (text.length * (text.length +1)) / 2;
setInterval(()=>{
for(let i = 0; i <= text.length; i++) {
setTimeout(() => {
container.innerHTML = text.substr(0, i)
}, 500+500*i)
}
},sum*500)
}
let x = "hello"
typer(x)
<span id="typer"></span>
Upvotes: 0
Reputation: 3049
You need to use one setInterval()
that runs each 1000ms, and when it finishes the task you need to stop it by using clearInterval
, check this link to understand better how to use it.
Try this code:
const container = document.getElementById('typer')
function typer(text) {
const textLength = text.length
let i = 0
const writter = setInterval(() => {
if ( i === textLength ) {
clearInterval(writter)
} else {
container.innerHTML += text[i]
i++
}
}, 1000)
}
let x = "hello"
typer(x)
<p id="typer"></p>
Upvotes: 2
Reputation: 56
She setInterval function runs after set time, but does not block following code from executing before the timer is done.
try:
let i=0;//counter variable
setInterval(() => {// runs every second.
if (i <= text.length()){//run if the counter below the string length
container.innerHTML = text.substr(0, i);
}
i++;//increment counter
}, 1000)
Upvotes: 0