1

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

2 Answers 2

1

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()
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.