-1

How would I make the following change at an interval, say, 500, as opposed to being on page load?

I'm assuming this is doable

var textarray = [
"1",
"2",
"3",
"4",
"5"
];

function RndText() {
    var rannum= Math.floor(Math.random()*textarray.length);
    document.getElementById('ShowText').innerHTML=textarray[rannum];
}

window.onload = function() { RndText(); }

Would there be a way to make the script read from say, an external .txt file? As opposed to an Array within the document itself?

j08691
  • 204,283
  • 31
  • 260
  • 272
user2378230
  • 21
  • 1
  • 4

2 Answers2

0

you can use setInterval() to accomplish what you are looking for. Simply call your function from within your function to ensure that it will continue to run after x seconds.

you can save this javascript into somefile.js and simply put this in your html file, <script src="somefile.js"></script>

var textarray = [
"1",
"2",
"3",
"4",
"5"
];

function RndText() {
    //wait 5 seconds
    setInterval(function(){
        var rannum= Math.floor(Math.random()*textarray.length);
        document.getElementById('ShowText').innerHTML=textarray[rannum];
    }, 5000);
}

window.onload = RndText;
Rayon
  • 36,219
  • 4
  • 49
  • 76
stackoverfloweth
  • 6,669
  • 5
  • 38
  • 69
0

For your first question, you need to add a setInterval call. (see: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval)

var textarray = [
"1",
"2",
"3",
"4",
"5"
];

function RndText() {
    var rannum= Math.floor(Math.random()*textarray.length);
    document.getElementById('ShowText').innerHTML=textarray[rannum];
}

window.onload = function() { setInterval(RndText, 500); }

For your second question, file reading is tricky and not generally a good idea if not truly necessary. This other question should be helpful: Reading file contents on the client-side in javascript in various browsers

Community
  • 1
  • 1
Jess Jacobs
  • 1,137
  • 1
  • 8
  • 19
  • This worked too, but I did however use the first answer, first. Thank you for your tip about trying to read from an external source though. – user2378230 Oct 06 '15 at 18:54