I have searched high and low for a solution to this (that I can understand) and have yet to find one.
Fiddle here https://jsfiddle.net/the_o/a7dwp41s/
The Goal: To have the text change after a set period of time (for example 1 second).
The Problem: The timing is not accurate at all. It's not apparent in the fiddle but on my page the text sometimes changes waaaay too fast. Also sometimes the loop will just stop. I know that setTimeout is not accurate from reading other Stack Overflow answers, but have not come across a good solution for running a function after a set period accurately. I'd appreciate some help.
The HTML:
<span class="text-center"><span class="top-line">A heading here</span>
<br><span class="bottom-line">There once was a...<br>
<span id="changeTextMobile"></span></span>
</span>
The Javascript:
var text = ["carrot", "potato", "tomato", "lettuce", "radish", "cabbage", "melon", "cucumber"];
var elem = document.getElementById("changeTextMobile");
var counter = 0;
function rotate_text() {
elem.innerHTML = text[counter];
if (counter < 8) {
counter++window.setTimeout(rotate_text, 1200);
}
if (counter == 8) {
counter = 0;
}
}
rotate_text();
Here's the fiddle again: https://jsfiddle.net/the_o/a7dwp41s/