Reputation: 123
My goal with this was to create a div that runs through array items in rotation and also start immediately when the browser loads rather than wait to start. It starts working perfectly at first but after a while, it starts rotating between the array items crazy fast. Naturally that makes the browser slower. Why would this happen? How can I fix this?
var arr = ["<h2 class='text-center'>For the best choice in compounding… Choose Alvix</h2>", "<h2 class='text-center'>We strive to become more self sufficient. <br>For you. For Alvix. For Life.</h2>", "<h2 class='text-center'>Alvix… Providers of Solutions</h2>"
];
var i = 0;
var timeout;
function doStuff() {
document.getElementById('quote').innerHTML = arr[i];
i++;
if (i >= arr.length){
i=0;
}
timeout = setInterval(doStuff,4000);
}
doStuff();
Upvotes: 1
Views: 817
Reputation: 922
use setTimeout
insteaded of setInterval
you call your function every time it sets new interval so logical will find it go crazy,
you have 2 solution
To clear the interval with clearInterval
intrval = null
function doStuff(){
// logic...
if(intrval) clearInterval(intrval);
intrval = setInterval(doStuff, 4000);
}
doStuff();
Use SetTimeout
function doStuff(){
// logic...
setTimeout(doStuff,400);
}
doStuff();
Upvotes: 1
Reputation: 4050
Move the setInterval out of the doStuff function. Right now you are adding another 4 second timer every 4 seconds. This will call doStuff
immediately then every four seconds after.
var arr = ["<h2 class='text-center'>For the best choice in compounding… Choose Alvix</h2>", "<h2 class='text-center'>We strive to become more self sufficient. <br>For you. For Alvix. For Life.</h2>", "<h2 class='text-center'>Alvix… Providers of Solutions</h2>"];
var i = 0;
var timeout;
function doStuff() {
document.getElementById('quote').innerHTML = arr[i];
i++;
if (i >= arr.length){
i=0;
}
}
timeout = setInterval(doStuff,4000);
doStuff();
Upvotes: 3
Reputation: 943510
setInterval
calls a function every time period.
You are calling setInterval
inside a that function, so every time period you start another loop.
You start with one interval. After 4 seconds you have 2. 4 seconds later each of those creates another one and you have 4. Then 8. Then 16.
Replace the line doStuff();
with timeout = setInterval(doStuff,4000);
.
Upvotes: 1
Reputation: 22395
You keep on setting new intervals each recurse. Set the interval outside of the function, so that when you call it, it's not reiterating its declaration.
function doStuff() {
document.getElementById('quote').innerHTML = arr[i];
i++;
if (i >= arr.length){
i=0;
}
}
var timeout = setInterval(doStuff,4000);
Upvotes: 1