Solved

javascript timeout for in loop

Posted on 2012-03-21
14
348 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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 

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

The New “Normal” in Modern Enterprise Operations

DevOps for the modern enterprise offers many benefits — increased agility, productivity, and more, but digital transformation isn’t easy, especially if you’re not addressing the right issues. Register for the webinar to dive into the “new normal” for enterprise modern ops.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Returning a value from a class function to a partial view in MVC5 7 29
Angular won't showing my array result in HTML 3 27
Html value of radio 14 30
Search Item in Table 2 23
This article explains how to prepare an HTML email signature template file containing dynamic placeholders for users' Azure AD data. Furthermore, it explains how to use this file to remotely set up a department-wide email signature policy in Office …
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
Any person in technology especially those working for big companies should at least know about the basics of web accessibility. Believe it or not there are even laws in place that require businesses to provide such means for the disabled and aging p…
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…

829 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