Проблема в том, что вы вызываете функцию 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; }