Yaroslav
Yaroslav

Reputation: 417

Break infinite loop user input nodejs

I have the following javascript code

let run = true
while (run){
   await page.waitFor(1000);
   timer++;
   console.log('timer',timer);
   //here it is necessary to somehow catch user input and end the cycle
   if(input == true){
        run = false;
   }
}

Ctrl + C completes the program fully, and I would only like to exit this cycle

Upvotes: 1

Views: 1301

Answers (2)

Yaroslav
Yaroslav

Reputation: 417

Here is an example of an infinite loop without blocking Event Loop
Break while loop happens when esc is pressed
Program terminate with ctrl + c

const sleep = require('await-sleep');
let run = true;
let timer = 0;

readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);

process.stdin.on('keypress', (str, key) => {
    console.log(str, key, run);
    // Conditions on key
    if(key.name == 'escape'){
        run = false;
    }  
    if(key.name == 'c' && key.ctrl == true){
        process.exit(1);
    }
})

async function init(){
    while (run){
        await sleep(1000);
        timer++;
        console.log('timer',timer);
    }
}
init()

Upvotes: 1

Tizio Fittizio
Tizio Fittizio

Reputation: 529

You can do this using readline and raw mode

const readline = require('readline');

readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);

process.stdin.on('keypress', (str, key) => {
  // Conditions on key
  input = true;
})

// You can start your loop here

A note on enabling raw mode:

When in raw mode, input is always available character-by-character, not including modifiers. Additionally, all special processing of characters by the terminal is disabled, including echoing input characters. CTRL+C will no longer cause a SIGINT when in this mode.

You may want to set a key for exit the program correctly

Upvotes: 0

Related Questions