Использование таймера для печати отдельных элементов массива с заданными интервалами - PullRequest
0 голосов
/ 27 января 2019

У меня есть множество стран.Я хочу печатать элементы массива или страны от начала до конца каждые две секунды.

Попытка с использованием функции setInterval () и цикла for для этого.

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);

Я ожидаю, что элементы массива будут напечатаны от начала до конца с новым элементомпечатается каждые две секунды.Вместо этого весь массив печатает все сразу.Как я могу это исправить?

Ответы [ 2 ]

0 голосов
/ 27 января 2019

Проблема в том, что вы вызываете функцию printCountries каждые 2 секунды, а функция printCountries печатает весь массив countries каждый раз, когда он вызывается.

Для достижения желаемого результата вы можете использовать Генератор Функция

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; }

Вы можете переместить логику очистки интервала из функции generator, чтобы упростить ее

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; }
0 голосов
/ 27 января 2019

Вам не нужен цикл.Интервал действует как циклический механизм, потому что он работает непрерывно, каждые 2 секунды.

Ваша функция должна просто напечатать один элемент массива на основе индекса, который увеличивается каждый раз, когда вызывается функция.

Смотрите встроенные комментарии:

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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...