Home > Mobile >  javascript: stop certain loops and not others [enable/disable]
javascript: stop certain loops and not others [enable/disable]

Time:09-18

How could I enable/disable certain loop that contains user input

const prompt = require('prompt-sync')();
const readline = require('readline');

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

process.stdin.on("keypress", (str, key) => {
    if(key.name == "a") {{var fruit = prompt('input');}
function loop() {
console.log("test 123123 " fruit)}

time = setInterval(function(){loop()},6000)}})
test 123123 apple  (loop1/userinput1)
test 123123 orange (loop2/userinput2)

how could I stop just the orange loop and keep the other and also how could i stop duplicates so that the same input can't be looping at the same time.

ex...

  • someone enters something like "apple"
  • it would start printing
  • then they also enters "orange"
  • they decide I don't wanna loop "orange" anymore they enter "orange" again that turns off "orange" but keeps printing "apple"

CodePudding user response:

You need to put the variable "time" to outer scope, and use clearInterval for each new input:

const prompt = require('prompt-sync')();
const readline = require('readline');

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

const map = new Map();
process.stdin.on("keypress", (str, key) => {
    if (key.name == "a") {
        { var fruit = prompt('input'); }
        function loop() {
            console.log("test 123123 "   fruit)
        }
        const oldID = map.get(fruit);
        if (oldID) {
            clearInterval(oldID);
            map.delete(fruit);
        } else {
            const time = setInterval(loop, 100);
            map.set(fruit, time);
        }
    }
    // if (key.name == 'c') { // <== just my code to kill process
    //     process.exit();
    // }
})

  • Related