?
Solved

javascript timeout for in loop

Posted on 2012-03-21
14
Medium Priority
?
355 Views
Last Modified: 2012-08-14
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!
0
Comment
Question by:hibbsusan
  • 8
  • 6
14 Comments
 
LVL 22

Expert Comment

by:Kim Walker
ID: 37748307
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
 

Author Comment

by:hibbsusan
ID: 37748885
Are global variables bad?
0
 
LVL 22

Expert Comment

by:Kim Walker
ID: 37749007
No. They are necessary. Any variable declared outside a function or loop is a global variable.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:hibbsusan
ID: 37749160
Is there a solution that can avoid the use of a global variable. There are several posts here that pretty definitely discourage them.
0
 

Author Comment

by:hibbsusan
ID: 37749203
Yeah, this tells me that redrawTimer isn't defined and it breaks the hasClass() function :(
0
 
LVL 22

Expert Comment

by:Kim Walker
ID: 37749261
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
 
LVL 22

Expert Comment

by:Kim Walker
ID: 37749298
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
 

Author Comment

by:hibbsusan
ID: 37749563
i have my var redrawTimer = setInterval(redrawColors,1000); inside another function, so clearInterval can't see it, i guess
0
 

Author Comment

by:hibbsusan
ID: 37749620
The code is like this. Simply to make a grid of randomly colored divs:

http://jsfiddle.net/WrccV/
0
 
LVL 22

Expert Comment

by:Kim Walker
ID: 37749751
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
 

Author Comment

by:hibbsusan
ID: 37749767
Okay, thank you for your help. Maybe someone else can take a crack at it.
0
 
LVL 22

Expert Comment

by:Kim Walker
ID: 37749845
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
 

Accepted Solution

by:
hibbsusan earned 0 total points
ID: 37753007
Yeah, I still got errors with that, but I got it figured out eventually. thanks for the help
0
 

Author Closing Comment

by:hibbsusan
ID: 37770395
figured it out.
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

CTAs encourage people to do something specific to show interest in your company, product or service. Keep reading to learn why CTAs should always be thought of as extremely important, albeit small, sections of websites.
Dramatic changes are revolutionizing how we build and use technology. Every company is automating, digitizing, and modernizing operations. We need a better, more connected way to work together as teams so we can harness the insights from our system…
The viewer will get a basic understanding of what section 508 compliance can entail, learn about skip navigation links, alt text, transcripts, and font size controls.
The viewer will the learn the benefit of plain text editors and code an HTML5 based template for use in further tutorials.
Suggested Courses

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question