Ber
Ber

Reputation: 695

Why isn't this javascript while loop running in node?

I'm trying to make it so the program repeatedly accepts input and repeats it back until "exit" is inputted. Right now the loop doesn't run, and I don't know why since the exit variable is set to false. Here's my code:

var read = require("read");
var exit = false;


function OutsideLoop (exit) {

while(exit === false){

        read({prompt: "> "}, function (err, result) {

        console.log("");
        console.log(result);
        console.log("Type in more input or type 'exit' to close the program.");

        if(result === "exit"){
            exit = true;};
        });


};

};


OutsideLoop();

Thanks for the help guys. I have a similar loop working using if/then instead of while, so I rewrote this one along the same lines.

Upvotes: 0

Views: 170

Answers (3)

Ry-
Ry-

Reputation: 224904

Pointy’s right about the parameter shadowing the outer variable you’ve declared. However, what you’ll end up with is a horrible busy loop. Node.js is event-based; use its events properly.

function promptUser() {
    read({prompt: "> "}, function(err, result) {
        console.log();
        console.log(result);
        console.log("Type in more input or type 'exit' to close the program.");

        if(result !== "exit") {
            promptUser();
        }
    });
}

promptUser();

Upvotes: 1

willy
willy

Reputation: 1490

You aren't passing exit when you call the function. It should be:

    OutsideLoop( exit );

On the last line.

Upvotes: 0

Pointy
Pointy

Reputation: 413720

You've declared "exit" as a parameter to the function, so the outer declaration has no effect on the logic inside the function. You don't pass anything to the function when you call it, so "exit" is undefined and the === test fails.

If you either pass "exit" to the function, or else take out the parameter from the function declaration, it'll work — maybe. That "read" function is asynchronous, so I'm not sure how node will behave.

Upvotes: 5

Related Questions