Reputation: 57
The problem is that now, loop shows only last value of array which is 'o'
const h2 = document.querySelector('h2');
const title = document.querySelector('h1');
const word = ['h', 'e', 'l', 'l', 'o'];
function loop() {
for(let i = 0; i < word.length; i++) {
window.setInterval(() => {
console.log(word[i]);
title.textContent = word[i];
}, 1000)
}
}
loop();
<h1 />
<h2 />
Upvotes: 1
Views: 797
Reputation: 386560
For a small amout of intervals, I suggest to use setTimeout
instead and given them appropriate timeouts and a closure over the wanted character to add to innerHTML
of the element.
function loop(word, target) {
for (let i = 0; i < word.length; i++) {
setTimeout((c => () => target.innerHTML += c)(word[i]), (i + 1)* 1000);
}
}
loop('hello', document.querySelector('h1'));
<h1></h1>
If you still want to use setInterval
, you need to store the interval and clear this interval at the end of the word.
function loop(word, target) {
var interval = setInterval((i => () => {
if (i >= word.length) return clearInterval(interval);
target.innerHTML += word[i++];
})(0), 1000);
}
loop('hello', document.querySelector('h1'));
<h1></h1>
Upvotes: 2
Reputation: 585
Here is my understanding. This program should append hello for every one second.
This code works for me
html
<h1 />
<h2 />
js
const h2 = document.querySelector('h2');
const title = document.querySelector('h1');
const word = ['h', 'e', 'l', 'l', 'o'];
function loop() {
for(let i = 0; i < word.length; i++) {
window.setInterval(() => {
console.log(word[i]);
title.textContent += word[i] ;
}, 1000)
}
}
loop();
demo:
https://jsfiddle.net/Danielprabhakaran_N/sjzrx3qy/
Upvotes: 1
Reputation: 3464
If you want to change your title after 1 second for all the words in array you can start with index 0 and keep on setInterval till your index is less than word.length.
Like:
const h2 = document.querySelector('h2');
const title = document.querySelector('h1');
const word = ['h', 'e', 'l', 'l', 'o'];
loop(0);
function loop(index) {
setTimeout(() => {
if (index < word.length) {
title.textContent = word[index];
setTimeout(() => loop(index+ 1), 1000);
} else {
setTimeout(() => loop(0), 1000);
}
}, 1000)
}
Here I am setting the first element, and doing setTimeout for the next one
if index has exceeded the word length I have put else as well to reset the word loop.
Upvotes: 1
Reputation: 106
This is because you're doing the interval inside the loop, that means by the time you get to your 1s the i
is already at the end of your array i = 4
.
I think this is what you want?
let i = 0;
let interval;
const loop = () => {
console.log(word[i]);
if (word[i]) title.textContent += word[i];
else clearInterval(interval)
i ++;
}
interval = window.setInterval(loop, 1000);
Hope this helps
Upvotes: 1