2

I would like to display the text in the browser again and again in a new line every time, however there is only the first line of text appearing. How this code should be corrected? Besides, I know that setinterval() is to repeat a function, I'd like to ask how can it be used in this code? Thank you very much!

var text = document.getElementById('text');
text.innerText = create_random_string(20);


function create_random_string(string_length){
  var random_string = '';
  var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  for (var i, i = 0; i < string_length; i++) {
     random_string += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return random_string; 
}

document.write (
  create_random_string(20) + "<br>",
  create_random_string(20) + "<br>",
  create_random_string(20) + "<br>",
  create_random_string(20) + "<br>",
);
<div id="text"></div>

6
  • This will write a new line every 1 second: setInterval(function () {document.write (create_random_string(20) + "<br>")}, 1000); Commented Mar 5, 2022 at 9:04
  • What is meant by again and again in a new line every time? Commented Mar 5, 2022 at 9:08
  • @AnuragSrivastava Once the function starts, there is 20 characters displayed on the browser in one line. I'd like to keep displaying lines of 20 characters on the browser. Commented Mar 5, 2022 at 9:13
  • Does that mean clearing the previous line, or adding new lines below previous ones? Commented Mar 5, 2022 at 9:14
  • @AnuragSrivastava Adding new lines below previous ones Commented Mar 5, 2022 at 9:16

1 Answer 1

2

setInterval with 1000 milliseconds. write a random string in a new line every second.

var text = document.getElementById('text');

setInterval(function(){
  text.innerHTML += create_random_string(20) + '<br>';
}, 1000);


function create_random_string(string_length){
  var random_string = '';
  var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  for (var i, i = 0; i < string_length; i++) {
     random_string += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return random_string; 
}
<div id="text"></div>

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

Comments

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.