I'm missing some little thing.. prints the array but doesn't wait in between lines.
<script type="text/javascript">
function showLines()
{
arr =
[
"Hi!",
"Welcome!",
"Hello!"
]
var duration=2000;
document.getElementById("quotes").innerHTML=arr;
setTimeout('showLines()',duration);
}
</script>
That's because your just printing out the whole array, try this.
That should do the trick.
If you only want one at a time then replace
with
You never asked him to wait. You're just calling the same function every 2 seconds. Try with showLines(i), innerHTML += arr[i], and setTimeout(showLines,duration,i++)
Most answers here are re initializing your array on each iteration.It makes no sense to do that. You should do it like this:
This way it works, and your array, and i are only initialized once.
EDIT In response to comment:
The line
will convert
arr
into aString
by joining it with commas. Therefore, you will seeThis function is idempotent, which is probably not what you are going for. I think what you're missing is an index that lets you know which element of the array you are on the next time the function is executed, and replaces the content of the
quotes
element with the next item in the array.First of all, you should wrap your code in an
onload
ordomready
function. jQuery is good at this. You should usewindow.onload = myfunc;
to do this.Your code should look like this: