Could Someone Figure Out What Is Going Wrong Here?


So I built a project today, it is a Typing Game I made on CodePen.

I used setInterval() to repeatedly generate a random word as a <div>, and then use setInterval() again to make it move down the screen. The player needs to type out the letters in the word before the word reaches the bottom.

The gist of it is, every string that is generated and put onscreen also goes into an array inPlay. Then every keydown event adds the key value to an empty temp string and simultaneously checks the inPlay array for the presence of that string. Once an inPlay string is found, it is removed from the DOM and from the inPlay array, and the temp string is reinitialized to "". Also, any word that reaches the bottom will automatically be removed.

There are two issues I am having with the code:

  1. I set the setInterval() that generates the word elements to 1800 ms. But for the first minute or so of the game, it seems to create them at much shorter intervals, flooding the screen with words. It only levels off and reaches a steady rate after a minute or so.
  2. Sometimes, usually when there are a lot of words on the screen, some words will not register. I will literally type the exact word, and it won’t respond. Is this because there are so many setIntervals running, and something something event loop?

Thank you. Have a nice day.

I think the first issue could be the time, you’re calling genWord() with 1800ms on start but the fall speed is 1500ms which is also called on the start, so I changed this:
I changed the initial speed to 1800ms
let fallSpeed = 1800;
I also changed the start function, the setInverval part to this, since now the inital speed is 1800, then we use the same variable,:

setInterval(function() {
  }, fallSpeed)

I also changed the following in order to clear the invervals of words that have been deleted.

function genWord() {
  //Other code...
  const fallInterval = setInterval(function() {
    fall(newWord, fallInterval);
  }, fallSpeed);
function fall (item, interval) {
//Other code...
    if ... {
         //code here
        missed.textContent = missCount;

Try that, and let me know if that’s what you meant.


I used the same fallSpeed variable for both setIntervals, and the first issue seems to be fixed. It was also a great idea to set the generate and fall speeds to the same time interval.

As for clearing the intervals of dead words, I did some research and it turns out that intervals are automatically cleared when an element gets deleted from the DOM. So yay. If not, I would’ve had to dynamically generate a setInterval variable using each new word’s id, or something.

Thank you very much for your feedback.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.