0

I'm trying to create a simple JS that will get random arrays and post them via div container. Here's what I have so far, now keep in mind I'm horrible with JS.

function timedMsg() {
    currMsg++;
    document.getElementById('timedMsgDiv').innerHTML = msgArr[currMsg % msgArr.length];
};

function init() {
    currMsg = -1;
    msgArr = Array('Computer.', 'Uploading', 'Random');
    timedMsg();
    var t = setInterval("timedMsg()", 50);
};

window.onload = init();

It only gets 'Computer' and then does not flip through them randomly or loop or anything. Any reason why? Here's my JSFiddle: http://jsfiddle.net/R8SYf/

ErraticFox
  • 1,363
  • 1
  • 18
  • 30

2 Answers2

2

Pass the function name to setInterval(), like this:

var t = setInterval(timedMsg, 2000);

http://jsfiddle.net/R8SYf/6/

Niklas
  • 13,005
  • 23
  • 79
  • 119
1

There are a few problems in your code:

1) When you pass a string to setInterval you trigger eval and your function is run in the global context, you don't want this. To fix it simply pass a reference to the function; rebember functions are objects too:

var t = setInterval(timedMsg, 2000);

2) The window.load event expects a function but you're assigning the returned value of the init function which is undefined. Like in the case above you need to pass a function object, not execute the function:

window.onload = init;

3) Your fiddle is set-up to load the code in the onLoad event, but you're assigning your own function. You need to change the behavior to No wrap - in <head>.

4) Although is works, using the Array constructor to create arrays is not good practice. Simply use the literal syntax:

msgArr = ['Computer.', 'Uploading', 'Random'];

Fixed http://jsfiddle.net/R8SYf/11/

elclanrs
  • 92,861
  • 21
  • 134
  • 171