سؤال

I want to create a delay between two document.writes. I used setTimeout to do so, but once it executes, it writes over the previous text. I would like to be able to display text, wait some delay, the display some other text below it without erasing any previous text. This code is appending to an otherwise empty HTML file. Also, I haven't had any success with using <br> for this.

var numOfDice = prompt("How many dice?");
var numOfSides = prompt("How many sides on these dice?");

var rollDice = function(numOfDice) {
    var rollResults = []; 

    for (var i = 0; i < numOfDice; i++) {
        rollResults[i] = Math.floor((Math.random() * numOfSides) + 1);
    }

    return rollResults;
}

var printResults = function() {
    var i = 0;
    while (i < rollResults.length - 1) {        
        document.write(rollResults[i] + ", ");
        i++;
    }

    document.write(rollResults[i]);
}

alert("Roll the dice!");


var rollResults = rollDice(numOfDice);

printResults();
setTimeout(function() {document.write("These numbers...")}, 1000);
هل كانت مفيدة؟

المحلول

First, take a look at this answer why you shouldn't be using document.write.

Then, after you understand why using document.write is bad practice, you can replace it with element.appendChild.

For more information about the function, visit the Mozilla Development Network.

Code example:

var numOfDice = prompt("How many dice?");
var numOfSides = prompt("How many sides on these dice?");

var rollDice = function(numOfDice) {
  var rollResults = []; 

  for (var i = 0; i < numOfDice; i++) {
    rollResults[i] = Math.floor((Math.random() * numOfSides) + 1);
  }

  return rollResults;
}

var printResults = function() {
  var i = 0;
  while (i < rollResults.length - 1) {
    var node = document.createElement("p");
    node.innerHTML = rollResults[i] + ", ";
    document.querySelector("body").appendChild(node);
    i++;
  }
  var node = document.createElement("p");
  node.innerHTML = rollResults[i];
  document.querySelector("body").appendChild(node);
}

alert("Roll the dice!");

var rollResults = rollDice(numOfDice);

printResults();
setTimeout(function() {
  var node = document.createElement("p");
  node.innerHTML = "These numbers...";
  document.querySelector("body").appendChild(node);
}, 1000);

Note that this code will show each rolled dice on a new line, since I'm creating a new p element for every roll. If you want them to appear on the same line, create one p element, and then in the while loop, append the rollresult to that p elements `innerHTML´ .

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top