Do something within a JavaScript array for loop - javascript

I am trying to figure out a way of how to loop through an array, do something with that array[index] pause function for x seconds and move to next index in that array.
That is what I achieved so far. It prints out the whole array, but I need it to print out only one value, do something with it, then proceed to the next one and so on.
var destinations = ['Greece', 'Maldives', 'Croatia', 'Spain'];
var index = 0;
for (index = 0; index < destinations.length; index++){
console.log(destinations[index]);
};

You could take the iteration protocols with an implementation of Symbol.iterator in Array#[##iterator]() and iterate until no more elements are available.
var destinations = ['Greece', 'Maldives', 'Croatia', 'Spain'],
gen = destinations[Symbol.iterator]();
interval = setInterval(function () {
var g = gen.next();
if (g.done) {
clearInterval(interval);
return;
}
console.log(g.value);
}, 1000);

You can use setTimeout to do this.
var time_between_steps = 1000
var destinations = ['Greece', 'Maldives', 'Croatia', 'Spain']
var index = 0
function nextItem(){
// do things here with destinations[index]
console.log(destinations[index])
index++
// if we have not yet reached the end of the array, run nextItem again after time_between_steps
if(index<=destinations.length-1)
setTimeout(nextItem,time_between_steps)
}
nextItem()

setTimeout can be used here:
Basically, you can define a method processItem and call it with the current parameter. Also the delay can be set with a variable.
After the delay, the method is called with a parameter.
var delay = 1000; // 1 sec
var destinations = ['Greece', 'Maldives', 'Croatia', 'Spain'];
var index = 0;
function processItem(item){
console.log("Item " + item);
// do stuff
}
function iterate(index){
processItem(destinations[index]);
index++;
if (index < destinations.length){
setTimeout(iterate, delay, index);
}
}
iterate(index);

Related

setInterval function not stopping when array length is reached

I have a simple setInterval function that is done inside of a for loop. My goal is that I want the function to run on each position in the array, and once it reaches the end, I want it to stop. However, this is not happening. The timeout function is continuing to run infinitely. Can anyone explain where I'm going wrong and what I need to do to fix this?
JS
Keyhole.bufferArray = [Keyhole.twoMileBuffer, Keyhole.fiveMileBuffer, Keyhole.tenMileBuffer, Keyhole.twentyFiveMileBuffer];
var ticker = -1;
for(var i = 0; i < Keyhole.bufferArray.length; i++){
var populateServices = setInterval(function(){
++ticker;
addBuffersToService(Keyhole, i);
if(ticker >= Keyhole.bufferArray.length - 1){
ticker = -1;
clearInterval(populateServices);
}
}, 1000)
}
function addBuffersToService(Keyhole, index){
console.log(Keyhole);
}
Because you have a for loop that is making an interval for every index of the array. You should not be using the for loop if you are looping over the array with the interval. Remove the for loop.
The problem is that you overwrite your interval handler in loop. I suggest you to kepp handlers in array and remove them according to iterator varialble:
var ticker = -1;
var populateServices = [];
for(var i = 0; i < Keyhole.bufferArray.length; i++){
populateServices[ticker + 1] = setInterval(function(){
...
clearInterval(populateServices[ticker + 1]);
ticker = -1;
Note that array identifiers should be positive numbers so you should add +1 inside handlers array.
And don't forget to set ticker to -1 after clearInterval invokation.

jQuery/JavaScript delay and display

I want to cycle through an array and display each element individually, and then remove it. Sort of like this fiddle, but I don't want it to go forever.
I tried using jQuery because I thought it would be easier, but I am clearly missing something. Can anyone help?
Here is my attempt, but it just goes straight to the last element in the array.
var list = [1,2,3,4,5,6];
var length = list.length;
for(i = 0; i < length; i++) {
$('#nums').html(list[i]).delay(750);
}
Oh, and I don't care if it's jQuery or vanilla JavaScript. Either is fine by me.
$(document).ready(function(){
var list = [1,2,3,4,5,6];
var length = list.length;
var i = 0;
var ivl = setInterval( function () {
if (i < length) {
$('#nums').html(list[i]).delay(750);
i++;
}
else {
clearInterval(ivl);
}
}, 750);
});
The (pretty clever) example uses the fact that the modulus operator (%) gives you remainder, which is periodic, so you can use it to cycle through your array by taking the remainder of an infinitely increasing number divided by the length of your list.
If you want it to stop, however, you can just do a check to see if you've finished cycling through the list:
var list = [1, 2, 3, 4, 5, 6];
var length = list.length;
var i = 0;
var finished = false;
function repeat() {
if (!finished) {
document.getElementById('nums').innerHTML = list[i % length];
i++;
if (i === length) {
finished = true;
}
} else {
clearInterval(interval);
}
}
var interval = setInterval(repeat, 750);
<div id="nums"></div>
Late to the party but wouldn't it be better to use setTimeout rather than setInterval just in case the code executed on each iteration takes longer than the interval duration? I mean, I know it's not an issue in this instance but it's just a better/safer way to do this sort of thing.
$(document).ready(function(){
var list = [1,2,3,4,5,6];
var length = list.length;
var i = 0;
(function next(){
if (i < length){
$('#nums').html(list[i++]);
setTimeout(next,750);
}
})();
});
http://jsfiddle.net/zLexhdfp/3/

arrayname.forEach( function(element){ });

I have a successfully populated array that contain string elements.
And I recently learned about the forEach() of JavaScript
arrayname.forEach(
function(element){
// some statements
}
);
How can I make it work so the "some statements" only run once every three seconds? I tried setInterval and setTimeOut but it did not give me the result I desired. Thanks
I tried this as well
arrayname.forEach( function(element){ }).delay(3000);
but it still did not give me the result I wanted. :(
This function will do it - it's worth avoiding setInterval wherever possible - it has issues where it doesn't guarantee at least delay between calls, particularly if earlier calls have been queued up (perhaps because the window lost focus):
function forEachWithDelay(arr, callback, delay, thisArg) {
var index = 0, count = arr.length;
(function loop() {
if (index < count) {
callback.call(thisArg, arr[index], index, arr); // same as .forEach
++index;
setTimeout(loop, delay);
}
})(); // start the loop immediately
}
usage:
forEachWithDelay(arrayname, function(element, index) {
// do something
}), 3000);
NB: this will start the loop with zero delay for the first element.
var arr = ["Microsoft", "Google", "Apple"];
var i = 0;
function loop() {
alert( arr[i] );
i++;
if( i < arr.length ){
setTimeout( loop, 3000 );
}
};
loop();
This may be what you want:
var i=0;
var loop = setInterval(function(){
if(i < arrayname.length){
console.log(arrayname[i]);
i++;
}else{
clearInterval(loop);
}
},3000);
Here's how you can do it:
var index = 0;
var t = setInterval(function() {
console.log(arrayname[index++]);
if (index === arrayname.length) {
clearInterval(t);
}
}, 3000);
Try this:
$(document).ready(function () {
var array = ["first","second","third","fourth"];
var arr_length = array.length;
var index = 0;
callTime();
function callTime(){
setTimeout(function(){
index++;
if(index < arr_length){
callTime();
}
},1000);
}
});

case, setinterval and listing only selected arrays

I'm trying to make interval function, which will change selected div every 10seconds. When i'm on first page, i want it to show items from first array, when im on second i want array 2, etc. this is what i got so far:
var timedFunc = '';
var index= new Array(20)
index[0]="index1";
index[1]="index2.";
..
var indextwo= new Array(20)
indextwo[0]="index1";
indextwo[1]="index2";
var tmp = 0;
function display_index(nameofarray) {
if (tmp < 0) { tmp = nameofarray.length-1; }
if (tmp > nameofarray.length-1) { return false; }
document.getElementById('robot').innerHTML = nameofarray[tmp];
tmp = tmp + 1;
}
function indexInterval(m) {
switch(m) {
case 1: timeFunc = setInterval("display_index(index)",1000);
case 2: timeFunc = setInterval("display_index(indextwo)",1000);
case 3: timeFunc = setInterval("display_index(indexthree)",1000);
case 4: timeFunc = setInterval("display_index(indexfour)",1000);
}
}
To cycle through an array on an interval timer, you can pass the desired array to a function and then use that function to cycle through the array on an interval timer like this:
var index0 = ["text1", "text2", "text3"];
var index1 = ["text1", "text2", "text3"];
function startMyInterval(array) {
var index = 0;
var item = document.getElementById('robot');
setInterval(function() {
// if we reached the end of the array, start back at beginning
if (index >= array.length) {
index = 0;
}
item.innerHTML = array[index];
++index;
}, 10000);
}
// figure out which array of text values you want to use
// for this particular page index0 or index1
// and pass that array to startMyInterval()
startMyInterval(x);
This type of implementation avoids the switch statement and avoids passing text to setInterval(). It also uses a function closure to keep track of the state that the setInterval() callback needs.

Loop over array but with a time delay

I am trying to loop over an array. However, I would like to add a 15 second delay between each array value. This will write value 1 to console, then count down 15 seconds and write value 2 to console, and so on.
I'm not sure exactly how to do this. My code as of now just outputs the numbers 15 all the way to 1 on the console at once with no actual count down and no array values.
array
["l3", "l4", "l5", "l6", "l7", "l8", "l9", "l10", "l11", "l12", "l13", "l14", "l15", "l16"]
code
var adArray = [];
// get links with class adfu
var adfuClass = document.getElementsByClassName('adfu');
for (var i = 0; i < adfuClass.length; i++) {
var ids = adfuClass[i].id
var newIds = ids.replace(/tg_/i, "l");
adArray.push(newIds);
}
// get links with class ad30
var ad30Class = document.getElementsByClassName('ad30');
for (var i = 0; i < ad30Class.length; i++) {
var ids = ad30Class[i].id;
var newIds = ids.replace(/tg_/i, "l");
adArray.push(newIds);
}
// get links with class adf
var adfClass = document.getElementsByClassName('adf');
for (var i = 0; i < adfClass.length; i++) {
var ids = adfClass[i].id;
var newIds = ids.replace(/tg_/i, "l");
adArray.push(newIds);
}
// loop through array with all new ids
for (var i = 0, l = adArray.length; i < l; i++) {
var counter = 15;
var countDown = setTimeout(function() {
console.log(counter);
if (counter == 0) {
console.log(adArray[i]);
}
counter--;
}, 1000);
}
// loop through array with all new ids
var i = 0, l = adArray.length;
(function iterator() {
console.log(adArray[i]);
if(++i<l) {
setTimeout(iterator, 15000);
}
})();
Something like this?
There's a really simple pattern for this type of iterator, using closure scope to store a loop counter and a nested looper() function which runs the setTimeout() iterator. The looper() function actually iterates the loop count, so there is no need for a for or do/while construct. I use this pattern often, and it works really well.
EDIT: Modified the condition to check for loop > 1, not loop > 0, which logged Loop count: 0. This can be tweaked, and technically, the looper() here runs 16 times.
(function(){
var loop = 15;
var looper = function(){
console.log('Loop count: ' + loop);
if (loop > 1) {
loop--;
} else {
console.log('Loop end.');
return;
}
setTimeout(looper, 15000);
};
looper();
})();
http://jsfiddle.net/userdude/NV7HU/2
Use this function to make it easier to run:
function loopArr(arr, callback, time, infinite){
console.log('loop run');
var i=0,
total=arr.length-1;
var loop=function(){
// RUN CODE
console.log('loop arr['+i+']');
callback( arr[i] );
if (i < total ) {
i++;
} else { // LOOP END
console.log('loop end!');
if(!infinite) return;
i=0 //restart
}
setTimeout( loop, time);
}
loop()
}
To use this function execute this:
loopArr(arr, callback, time, infinite)
Where:
arr is the array we need to loop, it could be a jQuery selector
callback is the executed function with one argument returned which is the selected item
time is the timeout needed for delay
infinite is set true or false if we need the code to repeat itself forever
Example using animate.css :
var imgShowHide = function(elm){
var elm = $(elm); // select the item arr[i] via jQuery
elm.css('animation-duration','2s').show()
.addClass('animated bounceInRight')
.one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
elm.removeClass('animated bounceInRight')
.addClass('animated bounceInLeft')
.one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
elm.removeClass('animated bounceInLeft').hide()
})
});
}
// RUN
loopArr( $('#images > img'), imgShowHide, 4000, true);

Categories