1

I'm trying to get an input from a user to a console in node js a finite number of times, and run a function on each input. while or for loop doesn't work.

any help?

here is my code (litle simplified):

function foo(num)
{
 console.log(num)
}

function ReadUseInput()
{
 const readline = require('readline').createInterface({
     input: process.stdin,
    output: process.stdout
   }); 
    readline.question('Enter number...', num => 
  {
         foo(num)
       readline.close();
     });
}

//for (var i = 0; i < 10; i++)// this line isnt working - shows warning: MaxListenersExceededWarning: Possible EventEmitter memory leak detected
ReadUseInput()
3
  • The default limit for Event Emitter is 10. so you hit the limit by looping ten times Commented Aug 25, 2021 at 21:27
  • its not a limit, you can go way beyond that. its a warning that you do something fishy Commented Aug 25, 2021 at 21:28
  • await is the solution stackoverflow.com/questions/43638105/… Commented Aug 25, 2021 at 21:30

1 Answer 1

1

One solution could be to make the ReadUseInput() function take a number and decrement it to repeat a certain number of times:

function foo(num) {
 console.log(num)
}

function ReadUseInput(timesLeft) {
  // exit condition
  if(timesLeft <= 0) {
    return;
  }
  const readline = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
  }); 
  readline.question('Enter number...', num => {
    foo(num)
    readline.close();
    ReadUseInput(--timesLeft);
  });
}

ReadUseInput(10);
Sign up to request clarification or add additional context in comments.

6 Comments

the solution you offered @theusaf seems logical.. it doesnt throw warning anymore, but it still seem to run infinite times ( at least a lot more then 10) from my tests . the exit condition doesn't seem to work
Oh, my bad. I made a small mistake. I'll fix it quickly
it resolved it, thank you! I am a little curious to know what u changed that stopped it from looping infinitely, because I don't see a difference honestly @theusaf
Previously, I had done timesLeft--, which passes in the current value before decrementing it, which is why it went on forever. I changed it to --timesLeft to decrement, then pass in the value.
while on the topic, why recursion work in this case but for loop doesn't? what am i missing? what topic should i reference? (should i post this as a question?)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.