Aassuming the setTimeout
is calculcated by the amount of names (10000/2000), you can omit it entirely.
const TestNames = ["test1", "test2", "test3", "test4", "test5"];
//REM: https://developer.mozilla.org/en-US/docs/Web/API/setInterval
//REM: Passing a copy of TestNames to not alter the original
const interval = setInterval(function(listOfNames){
if(listOfNames.length){
//REM: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
const Username = listOfNames.shift();
console.log('Current name:', Username);
console.log(TestNames.length - listOfNames.length, ' names done.');
console.log(listOfNames.length % TestNames.length, ' names left.')
}
else{
//REM: Cancel the interval, if listOfNames has no more items
clearInterval(interval);
console.log('No names left.')
}
}, 2000, Array.from(TestNames));
Take the names from an array or list and pass them to my variable. How
can I do this ?
That depends on your requirements.
- Do you need to keep
TestNames
?
- Do you pick a random name?
- Do you just pick the next name in order?
In my example I pass a copy of TestNames
to the interval as listOfNames
. On each iteration I remove the first item from listOfNames
by using shift
which also returns that removed item and assign it to Username
. If listOfNames
has no more items, the interval gets cleared.