Solved

javascript timeout for in loop

Posted on 2012-03-21
14
345 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 21

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 21

Expert Comment

by:Kim Walker
ID: 37749007
No. They are necessary. Any variable declared outside a function or loop is a global variable.
0
 

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 21

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 21

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
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 

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 21

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 21

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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

This article discusses how to create an extensible mechanism for linked drop downs.
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
In this tutorial viewers will learn how to embed Flash content in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <object> tag to embed Flash content.: To specify that the object is Flash content, d…
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…

762 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now