I want to make a quiz app that requires a repeated loop
var first = "a", last = "c";
for(var i = first.charCodeAt(0); i <= last.charCodeAt(0); i++) {
console.log( eval("String.fromCharCode(" + i + ")") + " " );
}
this code will output a b c
in terminal so, I want to make it repeated till like 15 seconds.
// so it will be outputted like
a
b
c
a
b
c
... so on till 15sec
how to do it in JS? Do I have to return something? What should I return?
yes maybe the output its like these
a
b
c
a
c
... till 60 times
but how to do it?
I just make my argument in function
so I can call it repeatedly but your code is more bet practice i think
Hmmm, nice and thanks it’s work now. I even don’t think that way to solve this problem.
Again, thanks a lot.
A slightly more streamlined version which is slightly more flexible:
const displayLetters = (first, last) => {
let str = '';
for (let i = first.charCodeAt(); i <= last.charCodeAt(); i++)
str += String.fromCharCode(i) + ' ';
console.log(str + '\n');
};
const repeatDisplay = (firstLetter, lastLetter, numRepeats, totalTime) => {
const delay = totalTime / numRepeats;
for (let count = 1; count <= numRepeats; count++)
setTimeout(displayLetters, delay * count, firstLetter, lastLetter);
};
repeatDisplay('a', 'c', 60, 15000); // 60 repeats in 15 seconds
Creating a function like repeatDisplay like above allows you to specify the number of repeats and total time (in milliseconds) to display the repeats without out having to manually figure out the correct milliseconds to put in for the delay, if you decide to change your mind about how many repeats should show in a specific amount of time.
1 Like