Jevon Cochran
Jevon Cochran

Reputation: 1774

Using a timer to print individual elements of array at given intervals

I have an array of countries. I want to print the elements of the array, or the countries, from start to finish every two seconds.

Tried using the setInterval() function and a for loop to accomplish this.

var countries = ['US', 'UK', 'Canda', 'Mexico', 'Panama',         
                 'Dominican Republic', 'Brazil', 'Germany', 'France', 
                 'Portugal','Spain', 'the Netherlands']; 

function printCountries() {
    for (i = 0; i < countries.length; i++) {
        document.write(countries[i]);
        }
    } 

setInterval(printCountries, 2000);

I expect that the elements of the array will be printed from start to finish, with a new element printed every two seconds. Instead, the entire array prints all at once. How can I fix this?

Upvotes: 0

Views: 1542

Answers (2)

Scott Marcus
Scott Marcus

Reputation: 65855

You don't need a loop. The interval acts as a looping mechanism because it runs continuously, every 2 seconds.

Your function just needs to print one array element based on an index that gets incremented each time the function gets called.

See comments inline:

let output = document.querySelector("div");

var countries = ['US', 'UK', 'Canda', 'Mexico', 'Panama',         
                 'Dominican Republic', 'Brazil', 'Germany', 'France', 
                 'Portugal','Spain', 'the Netherlands']; 

let timer = null; // Will hold a reference to the timer
let index = 0;    // Keeps track of which array element to show next

function printCountries() {
   // Set the contents of the output element (the <div>) to its old
   // contents, plus the next country name and an HTML <br>. This is
   // what makes the contets of the <div> grow each time a new country
   // is iterated.
   output.innerHTML = output.innerHTML + countries[index] + "<br>";
   // Check to see if we've reached the end of the array.
   if(index === countries.length-1){
     clearInterval(timer);  // Cancel the timer
   } else {
     index++; // Increment the index so that the next time, we get the next country
   }
} 

// You'll want to stop the interval when you're done iterating the array
// so you need to set u a reference to it to refer to later.
timer = setInterval(printCountries, 2000);
<div></div>

Upvotes: 2

Yousaf
Yousaf

Reputation: 29334

Problem is that you call the printCountries function every 2 seconds and the printCountries function prints the entire countries array each time it is called.

To achieve the desired result, you can use generator function

const countries = ['US', 'UK', 'Canda', 'Mexico', 'Panama',
             'Dominican Republic', 'Brazil', 'Germany', 'France',
             'Portugal','Spain', 'the Netherlands'];

function* getCountry() {

  for(let i=0; i<countries.length; i++) {
     // clear the interval if current index is the last index of the array
    if(i === countries.length - 1) {
        clearInterval(interval);
    }

    yield countries[i];
  }
}

let country = getCountry();

const interval = setInterval(() => console.log(country.next().value), 2000);
.as-console-wrapper { max-height: 100% !important; top: 0; }

You can move the logic of clearing interval out of the generator function to simplify it

const countries = ['US', 'UK', 'Canda', 'Mexico', 'Panama',
             'Dominican Republic', 'Brazil', 'Germany', 'France',
             'Portugal','Spain', 'the Netherlands'];

function* getCountry() {
  for(let i=0; i<countries.length; i++) {
    yield countries[i];
  }
}

let country = getCountry();
let result;

const interval = setInterval(() => {
   result = country.next();
   result.done === false ? console.log(result.value) : clearInterval(interval);
}, 2000);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Related Questions