I've created a function that reads a 8 random usernames from an API website using fetch
fetch('https://api.github.com/users').then(function(response) {
response.json().then(function(users){
document.write("Highlighred Github users")
for (let i=0; i< 8; i++) {
document.write('<br>')
document.write((users[Math.floor(Math.random() *users.length)].login))
}
});
}).catch(err => console.error(err));
I'm trying to modify it such that the 8 random users being displayed change/update every 30 seconds with a new list. I've attempted to do such a thing through modifying the for loop to be a function that operates based on a timer. The following replaces the for loop code in the above
var myVar=setInterval(function(){myTimer()},30000);
function myTimer() {
for (let i=0; i< 8; i++) {
document.write('<br>')
document.write((users[Math.floor(Math.random() *users.length)].login))
}
However, this function is generating a new list of 8 random users every nth second rather than changing the existing one
You can not use document.write after the page loads. Add an element to the page. Set the text of that element.
const users = [
{ login: 'A' },
{ login: 'B' },
{ login: 'C' },
{ login: 'D' },
];
const elem = document.getElementById("user");
function showNext() {
user.textContent = users[Math.floor(Math.random() * users.length)].login
window.setTimeout(showNext, 3000);
}
showNext();
<div id="user"></div>
Better solution is using a shuffle so you do not repeat. And when you run out, you can either stop or reshuffle
function shuffle(array) {
let currentIndex = array.length, randomIndex;
while (currentIndex != 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
const users = [
{ login: 'A' },
{ login: 'B' },
{ login: 'C' },
{ login: 'D' },
];
const elem = document.getElementById("user");
function runNames() {
const shuffled = shuffle(users.slice());
function showNext() {
user.textContent = shuffled.pop().login;
const runNext = shuffled.length ? showNext : runNames;
window.setTimeout(runNext, 3000);
}
showNext();
}
runNames();
<div id="user"></div>