I am a self taught newbie at programming and I'm trying to play around with arrays, DOM and setInterval() method. I wrote a code that accesses the h1 tag of my html file and displays each element of an array at 1000 millisecond intervals in that tag. Unfortunately, the code runs successfully but displays "undefined" at the end of the execution. When I check the elements section of the Chrome Dev Tools, I realize that my h1 tag keeps blinking which I assume stipulates that my code keeps running even after all the elements in the array have been extinguished. I have used the filter method, clearTimeout() method and still get the same results. I will paste my code below. Hopefully I get a solution to my issue. Appreciate the feedback in advance!
function myFunction() {
const welcome = ["Hello", "My", "Name", "Is", "Philip", "Nice", "To", "Meet", "You!"];
for (let i = 0; i < welcome.length; i ) {
function subset() {
document.getElementById("heading").innerHTML = welcome[i ];
}
setInterval(subset, 1000);
return;
}
}
myFunction();
<h1 id="heading"></h1>
CodePudding user response:
You could reorganize this so that each function call sets up the next function call. This way you don't need to worry about keeping track of intervals to clear and it's easier to understand how i is being incremented. If you're not clear on how function.bind() works I recommend reading up on that, it's pretty useful.
function myFunction(i) {
const welcome = ["Hello", "My", "Name", "Is", "Philip", "Nice", "To", "Meet", "You!"];
document.getElementById("heading").innerHTML = welcome[i];
if (i < welcome.length - 1)
setTimeout(myFunction.bind(null, i 1), 1000);
} myFunction(0);
CodePudding user response:
You might find setTimeout
easier to manage. Here we call a function with the array, initialise the index, and then call an inner function.
This logs each word of the array. We increment the index, and then, if the index is less than the array length, we call the loop
function again.
// Declare your array, and cache your element
const welcome = ['Hello', 'My', 'Name', 'Is', 'Philip', 'Nice', 'To', 'Meet', 'You!'];
const heading = document.getElementById('heading');
function myFunction(arr) {
// Initialise the index
let index = 0;
// `setTimeout` calls `loop` if the
// index < than the array length
function loop() {
const el = arr[index];
// Add the word to the heading
// Depending on the index prefix a space to it
const word = index ? ` ${el}`: el;
heading.textContent = word;
// Increment the index
index;
// If the index < than the array length
// call the `loop` function again
if (index < arr.length) {
setTimeout(loop, 1000);
}
}
// Call `loop` for the first time
loop();
}
// Call `myFunction` with the array
// as an argument
myFunction(welcome);
<h1 id="heading"></h1>
Additional documentation