How to repeat loop in javascript

How to repeat loop in javascript
0.0 0

#1

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?


#2

How much time should there be between repeats? If you do not specify a time between repeats, there could easily be a million repeats in 15 seconds. A better question is what is the max number of times you want it to repeat?


#3

It its like 60 times,


#4

You want it to repeat 60 times?


#5

yes maybe the output its like these

a
b
c
a
c
... till 60 times

but how to do it?


#6

If you want it to repeat 60 times in about 15 seconds, then first you need to figure out how many seconds per repeat that will take. That turns out to be 0.25 seconds per repeat of delay which is 250 milliseconds per repeat. You could use the setTimeout function available in JavaScript to create the delay between repeats which will be nested in a for loop as below.

NOTE: I modified the display of the repeated letters to be on the same line.

const displayLetters = (first, last) => {
	let str = '';
	for (let i = first.charCodeAt(0); i <= last.charCodeAt(0); i++) {
		str += String.fromCharCode(i) + ' ';
	}
	console.log(str + '\n');
};

const repeatDisplay = (firstLetter, lastLetter, numTimes, delay) => {
	for (let count = 1; count <= numTimes; count++) {
		setTimeout(() => displayLetters(firstLetter, lastLetter), delay * count);
	}
};

repeatDisplay('a', 'c', 60, 250);

#7

I just make my argument in function so I can call it repeatedly but your code is more bet practice i think :slight_smile:

Hmmm, nice and thanks it’s work now. I even don’t think that way to solve this problem.

Again, thanks a lot.


#8

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.