javascript timeout for in loop

How can I make a timeout so that a function waits a second before it does something to the next element in the array it's for-inning through?

function hasClass(el, cssClass) {
    return el.className && new RegExp("(^|\\s)" + cssClass + "(\\s|$)").test(el.className);
}

function redrawColors() {

   var elements = document.getElementsByTagName('div');
   
   for ( current in elements ){
      
         var element = elements[current];
         if ( hasClass(element, "pixel") ) {
         //wait for 1s before doing something to each of these divs with the class pixel       
        
      }

   }
}

Open in new window


Thanks so much!
hibbsusanAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kim WalkerWeb Programmer/TechnicianCommented:
You could create a global counter and declare the elements variable globally. Then execute the function on a setInterval until the last div is reached.
function hasClass(el, cssClass) {
	return el.className && new RegExp("(^|\\s)" + cssClass + "(\\s|$)").test(el.className);
}

var elements = document.getElementsByTagName('div'), current=0;
function redrawColors() {
	var element = elements[current];
	if ( hasClass(element, "pixel") ) {
		//do something
	}
	current++;
	if (current = elements.length) {
		clearInterval(redrawTimer);
		current = 0;
	}
}
var redrawTimer = setInterval(redrawColors,1000);

Open in new window

0
hibbsusanAuthor Commented:
Are global variables bad?
0
Kim WalkerWeb Programmer/TechnicianCommented:
No. They are necessary. Any variable declared outside a function or loop is a global variable.
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

hibbsusanAuthor Commented:
Is there a solution that can avoid the use of a global variable. There are several posts here that pretty definitely discourage them.
0
hibbsusanAuthor Commented:
Yeah, this tells me that redrawTimer isn't defined and it breaks the hasClass() function :(
0
Kim WalkerWeb Programmer/TechnicianCommented:
Functions are all basically objects stored in global variables. I guess we'll have to do away with them, too. Just kidding.

The alternative is to create a master global variable that contains all your global values. In this case you only have two global variables, "elements" and "current." If you have other javascript that might potentially overwrite the value of one of these variables, you may want to use less common names for them.
0
Kim WalkerWeb Programmer/TechnicianCommented:
redrawTimer is definitely defined. At least until the cycle completes. At what point are you inserting the script? Can you post a link to the page with all the working (or not working) parts?
0
hibbsusanAuthor Commented:
i have my var redrawTimer = setInterval(redrawColors,1000); inside another function, so clearInterval can't see it, i guess
0
hibbsusanAuthor Commented:
The code is like this. Simply to make a grid of randomly colored divs:

http://jsfiddle.net/WrccV/
0
Kim WalkerWeb Programmer/TechnicianCommented:
I can't tell much from this. I need a working or non-working page to see what error is being generated and when. I can tell that you need to move the global variable declaration on line 5 to your page load function with the redrawTimer declaration so that the elements object is declared AFTER the divs have been added to the page. The setInterval length should also be 1000 instead of 100.
0
hibbsusanAuthor Commented:
Okay, thank you for your help. Maybe someone else can take a crack at it.
0
Kim WalkerWeb Programmer/TechnicianCommented:
I did have a couple of errors. Try this:
function hasClass(el, cssClass) {
    return el.className && new RegExp("(^|\\s)" + cssClass + "(\\s|$)").test(el.className);
}

var elements, current, redrawTimer;

function redrawColors() {
    console.log(elements.length);
    var element = elements[current];
    if ( hasClass(element, "pixel") ) {
        console.log(elements[current]);
    }
    current++;
    if (current == elements.length) {
        clearInterval(redrawTimer);
        current = 0;
    }
}

            
function getColors (){
    
    var r = Math.random();
    var g = Math.random();
    var b = Math.random();
    var a = Math.random();
    
    r = r.toFixed(2);
    g = g.toFixed(2);
    b = b.toFixed(2);
    a = a.toFixed(2);
    
    r = 255*r;
    g = 255*g;
    b = 255*b;
    
    r = Math.floor(r);
    g = Math.floor(g);
    b = Math.floor(b);
    
    
    var c = {
     
        r : r,
        g : g,
        b : b,
        a : a,    
        
    }

    return c;
}

$(document).ready(function(){

    
    var grid = "";
    //150
    for ( var g=0; g<=25; g++ ){
        
        grid +="<div class='break'>";
        //250
        for ( var i=0; i<=25; i++ ){
            
            var c = getColors();
            var b = getColors();
            grid += "<div id='"+g+"-"+i+"' class='fl pixel' style='background-color:rgba("+c.r+","+c.g+","+c.b+","+c.a+"); border:1px solid rgba("+b.r+","+b.g+","+b.b+","+b.a+")'></div>";
        }
        
        grid += "<div class='cb'></div>";
        grid += "</div>";
    
    }
    
    $('body').append(grid);

    elements = document.getElementsByTagName('div')';
    current=0;
    redrawTimer = setInterval(redrawColors,1000);;

});¿

Open in new window

0
hibbsusanAuthor Commented:
Yeah, I still got errors with that, but I got it figured out eventually. thanks for the help
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
hibbsusanAuthor Commented:
figured it out.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.