Constantly loop a javascript array and display results to div? - javascript

I have a bunch of testimonials for my site which are currently on a page and am trying to get a div to display each 1 at an interval of 5 seconds, if the array reaches the last value it should start back to beginning of the array again.
Here is what I have so far...
var testimonial = new Array();
testimonial[1] = "Rugby";
testimonial[2] = "Baseball";
testimonial[3] = "Cricket";
var length = testimonial.length
var i = 1;
setInterval(function() {
while (i <= length) {
$('#testimonials p').html(testimonial[i]);
++i;
if (i == length) {
i == 1;
}
}
}, 5000);
Any help would be great, thanks.

Try
var testimonial = ['Rugby', 'Baseball', 'Cricket'];
var numTestimonials = testimonial.length;
var index = 0;
setInterval(function() {
$('#testimonials p').text(testimonial[index]);
index = (index + 1) % numTestimonials;
}, 5000);
JavaScript arrays are 0-indexed and have handy array literal syntax. Using the modulus operator (%) is an idiomatic way of wrapping a counter back to 0 once it reaches a certain value.

You can try
setInterval(function() {
$('div').html(test[ (i = (i + 1) % length) ]) },
5000);

The function in setInterval is being called every 5 seconds. That means you display the 5 testimonials one after another really quick every 5 seconds instead of displaying them one after the other.
You should do something like:
var testimonial = new Array();
testimonial[1] = "Rugby";
testimonial[2] = "Baseball";
testimonial[3] = "Cricket";
var length = testimonial.length
var i = 0; // arrays start with 0
setInterval(function() {
$('#testimonials p').html(testimonial[i]);
i++;
if (i == length) i = 0;
}, 5000);

Many interesting answers, so one more won't hurt. :-)
You can bundle it all up in an immediately called function expression:
(function() {
var testimonials = ['Rugby', 'Baseball', 'Cricket'];
var i = 0;
setInterval(function() {
$('#testimonials p').text(testimonials[++i % testimonials.length]);
}, 5000);
}());

Related

have an array with colors that I want to rotate infinitely through setInterval

So I have an simple array that contains few colors and a function that adds those colors to the backgroundColor property to the body. I am using setInterval to run through the colors, but as it has gone through the array it stops. I would like it to just keep going, either to begin from the start or it could also go in reverse order. How would I do this?
let colors = ['crimson','dodgerblue','gold', 'deeppink'];
const body = document.body;
let index = 0;
function change() {
body.style.backgroundColor = colors[index++];
}
var timer = setInterval(change, 4000);
You just need a little bit of extra logic to check the index and reset it to 0 if it's gone beyond the end of the array.
The simplest way is to use the % "modulus" operator:
function change() {
index = (index + 1) % colors.length;
body.style.backgroundColor = colors[index];
}
You have to ensure the index reach the end of the array and if so, reset it.
Something like:
function change() {
index = index === colors.length - 1 ? 0 : index++;
body.style.backgroundColor = colors[index];
}
let colors = ['green','dodgerblue','gold', 'deeppink'];
const body = document.body;
let index = 0;
function change() {
console.log('going')
body.style.backgroundColor = colors[index++];
if(index == colors.length) {
index = 0;
}
}
var timer = setInterval(change, 1000);
I simply added some logic that if index reached the end of the array, reset it back to zero

How do I cycle through multiple lines with a javascript letter randomiser?

Ok so I have this code for a JavaScript letter randomiser that works perfectly fine, i'm just having trouble figuring out how i'd get it to produce more than just one line while still keeping my code relatively efficient.
Ideally id like it to say something like this and then cycle back to the start:
Hi, my name is Yeet
this is my website
I like making cool stuff
take a look around :)
Any help would be greatly appreciated :)))
window.onload = function() {
var theLetters = "abcdefghijklmnopqrstuvwxyz#%&^+=-";
var cntnt = "Hi, my name is Yeet";
var speed = 20; // ms per frame
var increment = 2; // frames per step
var clen = cntnt.length;
var si = 0;
var stri = 0;
var block = "";
var fixed = "";
//Call self x times, whole function wrapped in setTimeout
(function rustle(i) {
setTimeout(function() {
if (--i) {
rustle(i);
}
nextFrame(i);
si = si + 1;
}, speed);
})(clen * increment + 1);
function nextFrame(pos) {
for (var i = 0; i < clen - stri; i++) {
var num = Math.floor(theLetters.length * Math.random());
//Get random letter
var letter = theLetters.charAt(num);
block = block + letter;
}
if (si == (increment - 1)) {
stri++;
}
if (si == increment) {
// Add a letter;
// every speed*10 ms
fixed = fixed + cntnt.charAt(stri - 1);
si = 0;
}
$("#output").html(fixed + block);
block = "";
}
};
Make cntnt an array
var cntnt = ["Hi, my name is Yeet", "This is my website", "I like making cool stuff", "take a look around :)"];
and use pos % cntnt.length as the array index.
fixed = fixed + cntnt[pos % cntnt.length].charAt(stri - 1);

Passing count variable in setInterval function

I am attempting to step through the array and every 3 seconds change the innerHTML of some items in the DOM. This code currently goes straight from 0(mixed media artist) to 2(descriptor) and doesn't display 1(art educator) at all. And the console.log outputs 0 1 2 for each setinterval loop.
Can anyone see what I am doing wrong to get this to work properly?
var heroItems = ['galleries', 'workshops', 'exhibitions'];
var heroBtns = ['view', 'sign UP', 'VIEW'];
var heroURLs = ['#', '#', '#'];
var descriptions = ['mixed media artist', 'art educator', 'descriptor'];
setInterval(function() {
for (var i = 0; i < descriptions.length; i++){
console.log(i)
changeDescription(i);
}
}, 3000);
function changeDescription(i) {
var descriptor = document.getElementById('descriptor').innerHTML = descriptions[i];
var hero = document.getElementById('hero').innerHTML = heroItems[i];
var heroRef = document.getElementById('heroref').setAttribute('href', heroURLs[i]);
var heroBtn = document.getElementById('herobtn').innerHTML = heroBtns[i];
}
The problem is, you don't wait after each loop iteration. You only wait once, after changing the description 3 times.
In your case, you could also totally skip the loop.
var i = 0;
var timer = window.setInterval(function() {
changeDescription(i);
if (++i == descriptions.length) {
window.clearInterval(timer);
}
}, 3000);

How define a couple of setIntervals and clear them with delay

I need to randomly change characters of a text and after some delay fix them.
There is my code:
<h1 id="text" style="margin-top:100px;">SOME TEXT</h1>
<script>
var text = document.getElementById("text").innerHTML.split("");
var myArr = text;
for (i = 0; i < myArr.length; ++i) {
var handle = setInterval(function () { xyz(i) }, 100);
setTimeout(function (handle) {
myArr[i] = text[i];
clearInterval(handle);
}, (i) * 1000);
}
function xyz(index) {
myArr[index] = String.fromCharCode(Math.random() * 26 + 65);
document.getElementById("text").innerHTML = myArr;
}
</script>
It seems i have no a good understanding of how setInterval work! :(
EDIT:
With my code only text[text.length+1] character has change that mean passed parameter to xyx() function is last value of loop counter variable (after loop over). Now my question is how trigger setInterval() function with i = 0 ,1 ... , text.length.
Can someone guide me?
basicly setInterval execute a function with a iteration in time. and setInterval gives you a promise to cancel it any time you want.
var myPromise = setInterval(function(){
//some code here
},delayMiliseconds);
to cancel this code
clearInterval(myPromise);
Related to this question problem was wrong way to passing arguments to setInterval().the callback function i passed to setInterval() maintains a reference to "i" rather than the snapshot value of "i" as it existed during each particular iteration...
<h1 id="text" style="margin-top:100px;">SOME TEXT</h1>
<script>
var text = document.getElementById("text").innerHTML.split("");
var myArr = document.getElementById("text").innerHTML.split("");
for (i = 0; i < text.length; i++) {
var handle = setInterval(function (k) { xyz(k) }, 100,i);
setTimeout(function (handle, i) {
console.log(i);
console.log(text[i]);
myArr[i] = text[i];
clearInterval(handle);
}, (i) * 1000,handle,i);
}
function xyz(index) {
myArr[index] = String.fromCharCode(Math.random() * 26 + 65);
document.getElementById("text").innerHTML = myArr.toString();
}
</script>

Looping through array of strings - stay on last string

I have this function which loops through a list of strings every 5 seconds. I would like it to stay on the last string after finishing the loop.
What do I need to change here?
window.specialWorkBoxStyleOverride = function(workBox) {
var statusTextBox = $("<div class = 'status-description-box'></div>");
$(workBox).append(statusTextBox);
var statusTexts = ["Checking", "Updating", "Processing", "Saving"];
var idx = 0;
var updateStatus = function() {
statusTextBox.text(statusTexts[idx]);
idx = (idx + 1) % statusTexts.length;
setTimeout(updateStatus, 5000);
};
updateStatus();
};
Thanks a lot.
Right now your code always calls setTimeout, so it will loop forever. Checking whether you've reached the end of your list should be sufficient to stop this (and means you don't need the modular arithmetic any more):
var updateStatus = function() {
statusTextBox.text(statusTexts[idx]);
idx++;
if (idx < statusTexts.length) {
setTimeout(updateStatus, 5000);
}
};

Categories

Resources