[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

javascript timeout for in loop

Posted on 2012-03-21
14
Medium Priority
?
354 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Survive A High-Traffic Event with Percona

Your application or website rely on your database to deliver information about products and services to your customers. You can’t afford to have your database lose performance, lose availability or become unresponsive – even for just a few minutes.

 

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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

This article discusses how to implement server side field validation and display customized error messages to the client.
Ready to get certified? Check out some courses that help you prepare for third-party exams.
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…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).
Suggested Courses

649 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