0

I am in need of assistance. I have created some code that puts the vowels in an interval. It is working fine, however, once it cycles through the 6 letters (aeiouy) it stops. How will I be able to make this loop continuously and loop through letters indefinitely?

Thanks in advance!

// Vowel string
var vowels = 'aeiouy'.split('');

// start button
levelButton2.addEventListener("click", function () {
    for (y = 0; y < vowels.length; y++) {
       setTimeout(() => getRandom(vowels), y*1000);
    }
});


// Function that gives me random letters

function getRandom (letters) {
    var randomSet = letters[Math.floor(Math.random() * letters.length)];
    console.log('set random' , randomSet)
    document.getElementById("demo3").innerHTML = randomSet;
};

1
  • Welcome to SO! It's a good idea to make your snippet runnable by including all relevant markup. See minimal reproducible example and thanks! Commented Jun 30, 2020 at 17:32

1 Answer 1

1

If you get rid of the For loop and just add the settimeout in your getRandom function it will continue non stop.

// Vowel string
var vowels = 'aeiouy'.split('');
var _timer;
var levelButton2 = document.querySelector(".levelButton2");
var levelButton3 = document.querySelector(".levelButton3");
// start button
levelButton2.addEventListener("click", function () {
   getRandom(vowels);
});

// stop button
levelButton3.addEventListener("click", function () {
   clearTimeout(_timer);
});


// Function that gives me random letters

function getRandom (letters) {
    var randomSet = letters[Math.floor(Math.random() * letters.length)];
    console.log('set random' , randomSet)
    document.getElementById("demo3").innerHTML = randomSet;
    _timer = setTimeout(() => getRandom(vowels), 1000);
};
<button type="button" class="levelButton2">START</button>
<button type="button" class="levelButton3">STOP</button>
<div id="demo3"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

Should clear the existing timer or skip scheduling if a timer exists on subsequent clicks of start

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.