Reputation: 177
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>
Upvotes: 2
Views: 80
Reputation: 618
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>
Upvotes: 2