I have written a small function to animate some multi line strings. It takes an array of strings that it will log. It uses set interval to run the function that will log the frames. Then when their are no frames left clear interval runs and a callback function is called. In my case the callback function is using the readlineSync module to wait for user input (.i.e user can select to continue or exit). Then the script waits for user input. Selecting continue will call the next function, selecting exit will exit.
Basically it runs as intended if after the animation begins the user presses no buttons. But if the user presses the 1 key (the continue key) during the animation, then once the animation is finished the readlineSync prompt flashes briefly and uses that input and continues (same goes for the 2 key and exit).
What I don't understand is how it is using input from before it was actually called? I know this is not a super conventional use case for node, but I would really like to understand what is happening and if there is a way to make this run as desired.
readlineSync has worked for me throughout the project, and I have also used the setInterval loop for other things such as game logic without any issues. It seems to only be an issue when setInterval and readlineSync are used in tandem.
Here's the link to the module: https://www.npmjs.com/package/readline-sync
Here is my simplified code. Thanks in advance for any help towards understanding!
Const readlineSync = require("readline-sync")
let myArray = ["testing", "this", "function"];
let animate = function(array, fps, callback){
let numberOfFrames = array.length;
let index = 0;
let animationLoop = function(){
console.clear();
console.log(array[index]);
index++;
numberOfFrames--;
if(numberOfFrames === 0){
clearInterval(animationLoopInterval);
callback();
}
}
animationLoopInterval = setInterval(animationLoop, 1000/fps);
};
let next = function(){
let answer = readlineSync.keyInSelect(["Continue", "Exit"]);
if(answer === 0){
console.log("Unfortunately this runs from input that came during the animation")
}else if(answer === 1){
process.exit();
}
};
animate(myArray, 1, next);