0

I would like to write a simply Java script (native) program which MUST use a while loop and do the following.

  • prompts user to enter a colour -
  • Then change the background to that colour.
  • keep prompting them to enter colour and keep changing the background colour until user does not enter anything in the prompt at which point the WHILE loop ends.

I have seen lot of variations of this tackled by using functions - but I want to achieve this only using WHILE loop.

1 Answer 1

1

You can loop until value of the prompt entered is null. However you won't see the color change until after you leave the loop because the command prompt is blocking.

while (true) {
  var color = prompt("enter color", "red");
  if (color === null) {
    break;
  }
  document.body.style.backgroundColor = color;
}

This "asynchronous" version allows the browser to paint between prompt to another. But no while here.

function prompt_then(then) {
  var color = prompt("enter color", "red");
  if (color === null) {
    return;
  }
  document.body.style.backgroundColor = color;
  window.setTimeout(then, 1);
}

prompt_then(prompt_then);

Sign up to request clarification or add additional context in comments.

8 Comments

thanks a lot. but, how come your first answer works eventhough it uses while loop?
@lollah mullah, prompt blocks the execution. The loop while is suspended until the function prompt returns a value. That happens when you click the "OK" button.
while loop is ok to use. It's just like for loop. Just don't make it endless because browser can't paint or respond when executing loops. If you need a non-blocking loop, you will need to use some sort of "out of loop" process using command like setTimeout . Which the other example explains
yes @ITgoldman. I understand the difference between the two example. but my question is how come the first example with the while loop works.
if I explain my understanding of execution, since the condition for while is true, it goes inside the loop, get the colour, checks if it is null, it is not. so changes the colour and loops, since no delay and the loop starts, how does browser has time to change the colour?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.