lollah mullah
lollah mullah

Reputation: 13

prompt and change background color in a loop with native javascript

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

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

Upvotes: 0

Views: 296

Answers (1)

IT goldman
IT goldman

Reputation: 19485

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);

Upvotes: 1

Related Questions