JavaScript - Slowing Down A Loop
I've written some code to execute a loop. It's all standard stuff using a for loop but the problem I have is that it is executed too quickly.
Between each iteration of the loop I want to insert a "pause" of, say, 40 or 50 milliseconds. I initially tried the setTimeout() function but I soon found out that wasn't right for use within a loop. What I want to achieve could be summed up as follows:- for (i = 1; i <= 100; i++) { dosomecode(); wait(50); } I've spent some time looking into this but couldn't get anything to work. If you haven't already guessed, I'm quite new to Javascript and any help would be appreciated. Similar TutorialsDear readers, Context: I have a dedicated GPS tracker that records every 3 seconds my location. What I want to do: Find the country, postal code, province, street and place from every coordinate. What my codes (javascript) does so far: - Create tables and inserts the coordinates into the table - Retrieves the country, streets etc from google with geocoder.geocode - Updates the tables with country, street etc. What is my problem: The first 1-50 retrieves is going quick, after that it slows down and after about 300 retrieves it is very slowwwwwwwwww. When I refresh my html page and start over, it is again quick to retrieve the data but will slow down again. I am using a time-out so that I am retrieving no more that 1 coordinate per 2-3 seconds. Because after I refresh the page and start directly over again, I do not think it is the limitations of retrieving from Google. I also canceled the writing to the database and only showing in the console the results and that is slowing down also after a few retrieves (so I think it is not a database problem). I am not a programmer and my code will probably not be 'clean'. I could realy need some help with this. I could send you my code so that you can try it yourself. I am using Chrome version 39.0.2171.95 m Reply With Quote 01-10-2015, 09:39 PM #2 Old Pedant View Profile View Forum Posts Supreme Master coder! Join Date Feb 2009 Posts 28,311 Thanks 82 Thanked 4,754 Times in 4,716 Posts Maybe the problem is that you are doing more timeout() calls than you think. Simple but horrible example: Suppose that every time you retrieve the data from the geocoder you set a timeout for the next retrieval. And then every time you fill in the tables, you *also* set a timeout for the next retrieval. That means that on the 2nd retrieval you will end up doing *FOUR* timeouts. And every 3 seconds you will be doubling the number of retrievals you do. Now clearly if you were really doing the above you would slow down horribly within 20 or 30 seconds. But suppose it is something more subtle than that, where you only do an extra timeout under certain conditions. That could very well explain it. That's not the only possible explanation, but it's where I would start. Maybe start logging the time, to the millisecond, of each retrieval...and see how many retrievals you are doing and how often. For that matter, just dump those numbers to the screen to see what they look like. Hey guys. I host a private website that I use to broadcast my DJ mixes live to my friends. I'm currently using a PHP script on the home-page to say whether I'm broadcasting currently, or if I'm offline. The script works great, but it really slows down the page loading time. Is there a way to have the page load, and then just have the "Status:" say "Checking..." until the PHP script can determine if I'm streaming or offline? This is my PHP code: PHP Code: <?php if (url_validate($link)) { echo "LIVE"; } else { echo "OFFLINE"; } ?> Thank you! Ok, I'm nearly pulling my hair out with this one. I have been looking at this code for two evenings now, and rewrote it 4 times already. It started out as jQuery code and now it's just concatenating strings together. What I'm trying to do: Build a menu/outline using unordered lists from a multidimensional array. What is happening: Inside the buildMenuHTML function, if I call buildMenuHTML, the for loop only happens once (i.e. only for 'i' having a value of '0'.) If I comment out the call to itself, it goes through the for loop all 3 times, but obviously the submenus are not created. Here is the test object: Code: test = [ { "name" : "Menu 1", "url" : "menu1.html", "submenu" : [ { "name" : "menu 1 subitem 1", "url" : "menu1subitem1.html" }, { "name" : "menu 1 subitem 2", "url" : "menu1subitem2.html" } ] }, { "name" : "Menu 2", "url" : "menu2.html", "submenu" : [ { "name" : "menu 2subitem 1", "url" : "menu2subitem1.html" }, { "name" : "menu 2subitem 1", "url" : "menu2subitem1.html" } ] }, { "name" : "Menu 3", "url" : "menu3.html", "submenu" : [ { "name" : "menu 3 subitem 1", "url" : "menu3subitem1.html" }, { "name" : "menu 3 subitem 1", "url" : "menu3subitem1.html" } ] } ]; Here is the recursive function: Code: function buildMenuHTML(menuData,level) { var ul; if (level == 1) { ul = "<ul id='menu'>"; } else { ul = "<ul class='level" + level + "'>"; } for (i = 0; i < menuData.length; i++) { menuItemData = menuData[i]; ul += "<li>"; ul += "<a href='" + menuItemData.url + "'>" + menuItemData.name + "</a>"; if (typeof menuItemData.submenu != 'undefined') { ul += buildMenuHTML(menuItemData.submenu,level + 1); } ul += "</li>"; } ul += "</ul>"; return ul; } Here is how the function is called initially: Code: buildMenuHTML(test,1); This is it's return value (with indentation added for readability): Code: <ul id='menu'> <li><a href='menu1.html'>Menu 1</a> <ul class='level2'> <li><a href='menu1subitem1.html'>menu 1 subitem 1</a></li> <li><a href='menu1subitem2.html'>menu 1 subitem 2</a></li> </ul> </li> </ul> 'Menu 2' and 'Menu 3' don't show up! I'm sure it's something small that I'm overlooking, but any help would be appreciated. Hi all I'm well aware that I can't post assignments here and expect an answer, however, I have been staring at this code for so long. I feel I am close to the solution (to get the correct output to the browser) but I just cannot get it to count how many moves it takes. I don't want an answer, but a nudge in the right direction would be very grateful. As you can see from the code and the output, it will attempt to write to the browser how many moves, but only '0'. Code: function rollDie() { return Math.floor(Math.random() * 6) + 1; } /* *searches for a number in a number array. * *function takes two arguments * the number to search for * the number array to search *function returns the array index at which the number was found, or -1 if not found. */ function findIndexOf(number, numberArray) { var indexWhereFound = -1; for (var position = 0; position < numberArray.length; position = position + 1) { if (numberArray[position] == number) { indexWhereFound = position; } } return indexWhereFound; } //ARRAYS that represent the board -- you do not need to change these //array of special squares var specialSquaresArray = [1,7,25,32,39,46,65,68,71,77]; //array of corresponding squares the player ascends or descends to var connectedSquaresArray = [20,9,29,13,51,41,79,73,35,58]; //VARIABLES used -- you do not need to change these //the square the player is currently on var playersPosition; //play is initially at START playersPosition = 0; //what they score when they roll the die var playersScore; //the index of the player's position in the special squares array or -1 var indexOfNumber; //MAIN PROGRAM //TODO add code here for parts (iii), (iv)(b), (v), and (vi) // start of question(iii) playersScore = rollDie(); document.write(' Sco ' + playersScore); playersPosition = playersScore + playersPosition; document.write(', Squa ' + playersPosition); indexOfNumber = findIndexOf(playersPosition, specialSquaresArray); if (indexOfNumber != -1) { document.write(', Ladder to Squa ' + connectedSquaresArray[indexOfNumber]); playersPosition = connectedSquaresArray[indexOfNumber]; indexOfNumber = -1; } document.write('<BR>') // end of question(iii) // start of question(iv)(b) while(playersPosition<=80) { playersScore = rollDie() document.write(' Sco ' + playersScore) playersPosition = playersPosition + playersScore document.write(', Squa ' + playersPosition) indexOfNumber = findIndexOf(playersPosition, specialSquaresArray) if(indexOfNumber != -1) { document.write(', Ladder to Squa ' + connectedSquaresArray[indexOfNumber]); playersPosition = connectedSquaresArray[indexOfNumber]; } document.write('<BR>'); } var countMoves = 0; while(countMoves <= 0) { document.write('You took ' + countMoves + ' moves to get out'); countMoves = countMoves + 1 } /*for (var countMoves = 0; countMoves < playersPosition; countMoves = countMoves + 1) { countMoves = countMoves + playersPosition; document.write('You took ' + countMoves + ' moves to get out'); }*/ // end of question(iv)(b) // start of question (v) /*if (playersPosition >=80) { document.write('The player is out'); }*/ // end of question (v) </SCRIPT> </HEAD> <BODY> </BODY> </HTML> Many thanks. Hello... Thanks for reading... I am getting an undefined error when i try to get a value from this array in the interior loop... Code: // This is the array I am trying to access AuditTable [0] = ["Visio Modifed date","Word Modified Date","User Status","User Comment","Last Audit","Audit Status","Audit Comment"] AuditTable [1] = ["11/23/2009 8:52:18 AM","missing","OK","user comment number 1","1/1/2009","ok","audit comment number 1"] AuditTable [2] = ["11/24/2009 12:21:19 AM","missing","Out of Date","Changes from 2008 not implemented","1/2/2009","Out of Date","needs update"] AuditTable [3] = ["11/22/2009 9:24:42 PM","missing","Incomplete","Document doesnt cover all possibilities","1/3/2009","Inadequate","needs update"] I have hard coded values and had success such as: Code: data = AuditTable[1][0] But when I put the vars associated with the loop in I get an undefined error - AuditTable[i] is undefined: Code: // produces error data = AuditTable[i][j] //Works but retrieves wrong data data = AuditTable[j][i] //Works but retrieves wrong data data = AuditTable[1][i] //Works but retrieves wrong data data = AuditTable[j][2] I must be trying to access the array incorrectly or something... I have defined all the vars, and tried many combinations, alerted the values of both vars so I can prove it is not a scope issue... Am I missing something obvious? Thanks much... Code: var reportArray=new Array(); var reportData, title, subTitle, data; for(i in parmarray)// loop thru AuditTable array and get values { title = '<div style="font-family:verdana; font-size:14px; font-weight:bold; margin:25px 0px 5px 30px">'; title += namearray[i][0]; title += '</div>'; reportArray.push(title);//Take compiled variable value and put it into array for(j=0; j < AuditTable[0].length; j++)// loop thru AuditTable array and get values { subTitle = AuditTable[0][j];//points to first row of AuditTable where the labels are data = AuditTable[1][0];//points to the current row where actual data is html = i + j +'<div style="font-family:verdana; font-size:12px; color:#696969; font-weight:bold; margin-left:30px;">'; html += subTitle; html += '</div><div style="font-family:verdana; font-size:12px; color:#a9a9a9; margin-left:30px; margin-bottom:10px">'; html += data; html += "</div>"; reportArray.push(html);// put results into array } } Hi, I am doing some studying and we was to create a small loop using either the for loop, while loop or do while loop. I chose to do the for loop because it was easier to understand, but I want to know how to do the same using the while loop. Here is the for loop I have, but I cant figure out how to change to while loop. Code: for (var i = 0; i < 5; ++i) { for (var j = i; j < 5; ++j) { document.write(j + ""); } document.write("<br />"); } output is equal to: 01234 1234 234 34 4 How do you make the same using a while loop? it wont loop, as long as you enter something in the name field it will submit. also how do i stop from submitting if all fields are not filled out? any help will be appreciated) ====== function checkForm(form) { var len = form.elements.length; var h=0; for (h=0; h<=len; h++){ if ((form.elements[h].value==null) || (form.elements[h].value=="")){ alert("Please enter "+document.myForm.elements[h].name); document.myForm.elements[h].focus(); return false; } return true; } } ===body-== <FORM NAME="myForm" METHOD="post" ACTION="http://ss1.prosofttraining.com/cgi-bin/process.pl"> Name:<BR> <INPUT TYPE="text" size="30" NAME="name"><br> Email address:<BR> <INPUT TYPE="text" size="30" NAME="email address" onBlur="emailTest(this);"><br> Phone number:<BR> <INPUT TYPE="text" size="30" NAME="phone number"><br> Fax number:<BR> <INPUT TYPE="text" size="30" NAME="fax number"><p> <INPUT TYPE="submit" VALUE="Submit Data" onClick="return checkForm(this.form);"> <INPUT TYPE="reset" VALUE="Reset Form"> </FORM> Hello all. I am faitly new at programming and have run into a little problem. I want to create a script that creates 2 random numbers, stored in 2 different variables and then compare them to eachother. there is two possible outcome of that comparison, either they are different or they are alike. If they are different i want to randomize a new set or numbers and make a other comparement, also to keep track on how many times i have created numbers. If they are alike i want to display the numbers and how many tries it took to get a matching pair. atm it looks like this <html> <body> <script> var x=(Math.floor(Math.random()*6)+1); var y=(Math.floor(Math.random()*6)+1); //creates two random int between 1 and 6 var throws = 1; //keep tabs on how many times we have thrown the dices if(x!=y) { x=(Math.floor(Math.random()*6)+1); y=(Math.floor(Math.random()*6)+1); throws=throws+1 }else{ document.write("you have rolled a pair. Dice 1 is: " +x +" and Dice 2 is: " +y +" and it took " +throws +" tries to get a pair."); } </script> </body> </html> How to get that into a loop? a really confused newbie scripter I have the following code which is almost completely working the way I need it to with the exception of the "downloadFile" value... Code: /*Regex list of download file extensions, pipe and backslash delimited. Looks for the period before the file type so it will work on download links with query parameters after it */ var downloadTypes = /\.pdf|\.doc|\.xls|\.zip|\.csv|\.ppt|\.rtf|\.pptx|\.docx|\.xlsx|\.wmv|\.mpg|\.exe|\.mp3|\.rar|\.wav/i; /*Regex list of on-site domains, pipe and backslash delimited. */ var onsiteDomains = /\mytestdomain1\.com|\mytestdomain2\.com|javascript|#/i; /*Used to unobtrusivly add events to objects*/ function unobtrusiveAddEvent (element,event,fn) { var old = (element[event]) ? element[event] : function () {}; element[event] = function () {fn(); old();}; } var links = document.links; if ( links ){ for(var i=0; i<links.length; i++) { if( links[i].href.match(downloadTypes) ){ unobtrusiveAddEvent( links[i], 'onclick' , function() { ntptEventTag('ev=download&eventPage=Download From: ' + escape( wa.currentDomain + wa.currentURL ) + '& downloadFile=' + escape( links[i] ) ); }); } if( !links[i].href.match(onsiteDomains) ){ unobtrusiveAddEvent( links[i], 'onclick' , function() { ntptEventTag('lk=1&ev=Exit Link'); }); } } } ...how do I grab the value of the href that was just clicked? links[i] is not working (it's just grabbing the href value of the last href in the loop). I am missing something simple for sure. Can anyone point out what I am missing? Thanks! Hello, I recently purchased a JavaScript book, and I am confused by one of it's examples. I was wondering if anybody could answer my question. Here is the example: for (loopCounter = 1; loopCounter<= 3; loopCounter++) { //execute this code } Now, what I need help with is the variable part. The book goes on to say: ""To keep track of how many times you have looped through the code, you need a variable to keep count" My question is: Why does the variable have the value of one and not another number? I'm very very new to JS, I understand that the loopCounter has to be les than or equal to 3 for the code to execute, and also that it is incremented by one each loop, but the book is not clear on why the value of the variable has been set to 1. If anybody could answer this question I would be very grateful, I hate moving onto the next stage of a book if I do not completely understand the previous topics. Thank you in advance I have a form that shows or hides divs based on what is chosen in a dropdown. There are 4 divs but only one is shown and the other 3 hidden based on dropdown selection. Inside each div are checkboxes with items for sale. I want to reset the checkboxes to unchecked and the line total values to 0 if the div is hidden. I've got the checkboxes to reset but I can't figure out how to set the line total values to 0 (There are 14 total so I'm trying to loop thru all of them and reset them.) This is what I have in the loop Code: for (var i = 0; i < form.elements.length; i++ ) { if (form.elements[i].type == 'checkbox') { form.elements[i].checked = false; } } // set line_totals to 0 for (var j = 0; j< form.elements.length; j++ ) { if (form.elements [j].name.substring(0,10) == 'line_total') { form.elements[j].value = ''; } } For those who read my other thread I finally scratched together the code to take a value from an XML file and add it to a select box as an option. Ofcourse it only does it once so I need to loop it. It's kinda complex though, here's a function line to add one option: addOption(document.people_form.People,name2,office2) And here's the code in the head: <script type="text/javascript"> //load xml file if (window.ActiveXObject){ var xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async=false; //Enforce download of XML file first. IE only. } else if (document.implementation && document.implementation.createDocument) var xmlDoc= document.implementation.createDocument("","doc",null); if (typeof xmlDoc!="undefined") xmlDoc.load("namedata.xml"); //Regular expression used to match any non-whitespace character var notWhitespace = /\S/ function getnames(){ //Cache "messages" element of xml file var nameobj=xmlDoc.getElementsByTagName("list")[0] //REMOVE white spaces in XML file. Intended mainly for NS6/Mozilla for (i=0;i<nameobj.childNodes.length;i++){ if ((nameobj.childNodes[i].nodeType == 3)&& (!notWhitespace.test(nameobj.childNodes[i].nodeValue))) { // that is, if it's a whitespace text node nameobj.removeChild(msgobj.childNodes[i]) i-- } } } if (typeof xmlDoc!="undefined"){ if (window.ActiveXObject) //if IE, simply execute script (due to async prop). getnames() else //else if NS6, execute script when XML object has loaded xmlDoc.onload=getnames } var name2=xmlDoc.getElementsByTagName("name")[0].firstChild.nodeValue; var office2=xmlDoc.getElementsByTagName("office")[0].firstChild.nodeValue; var officePH2=xmlDoc.getElementsByTagName("officePH")[0].firstChild.nodeValue; var mobile2=xmlDoc.getElementsByTagName("mobile")[0].firstChild.nodeValue; var email2=xmlDoc.getElementsByTagName("email")[0].firstChild.nodeValue; </script> <script type="text/javascript"> function addOption(selectbox,text,value ) { var optn = document.createElement("OPTION"); optn.text = text; optn.value = value; selectbox.options.add(optn); } </script> Could anyone give me a pointer on how to loop this so that it loads one option after another from the XML file? Thanks. Hey guys i've just been following a few tutorials and learnt how to do a for loop and a while loop, what is the major difference between the two? they seem quite similar? I know while loops are laid out a hell of a lot easier in my opinion!
Hi All, im trying to to use a for loop to loop through a drop down list of users and if there is a match between the user logged in and the drop down list i want to enable two fields, if the user logged in isnt in the drop down list i want to disable the two fields, but im having trouble looping through, iv tried ".value" with no avail.. heres my Script Code: var RequestingUser = document.getElementById('JoinersLeaversContent_cmbRequestingUser').text; var Authorisers = document.getElementById('JoinersLeaversContent_ddlAuthoriseId'); for (var i = 0; i < Authorisers.length; i++) { if (RequestingUser.text == Authorisers.value) { document.getElementById('JoinersLeaversContent_txtAuthoriserSig').disabled = false; document.getElementById('JoinersLeaversContent_txtDateSignedOff').disabled = false; } else { document.getElementById('JoinersLeaversContent_txtAuthoriserSig').disabled = true; document.getElementById('JoinersLeaversContent_txtDateSignedOff').disabled = true; } } So just to be clear, if the user logged in appears in the drop down box i want to enable the two fields, if they dont appear i want to disable the two fields Please help. Thank you hi there here's my problem, I want to alert each innerHTML of the tag "a" when mouse over, but it only alert when i insert "return false;" in the end of the loop, what's the problem? Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title></title> <script type="text/javascript" > function show(){ var linkIt = document.getElementsByTagName("a") for(var i=0; i<linkIt.length; i++){ linkIt[i].onmouseover = function(){ alert(linkIt[i].innerHTML); } return false; } } </script> </head> <body onload="show()"> <ul id="imagegallery"> <li> <a href="images/fireworks.jpg" title="A fireworks display">Fireworks</a> </li> <li> <a href="images/coffee.jpg" title="A cup of black coffee" >Coffee</a> </li> <li> <a href="images/rose.jpg" title="A red, red rose">Rose</a> </li> <li> <a href="images/bigben.jpg" title="The famous clock">Big Ben</a> </li> </ul> </body> </html> Trying to use a "for" loop to cycle through an array and compare values; if the values are equal, then it displays a message about the team, etc. Code: <html> <head> <title>Javascript Colors!</title> <script type="text/javascript"> var teamcolors = ["blue","orange","Auburn Tigers","Yuck!","black","red","Georgia Bulldogs","Congratulations!","yellow","black","Georgia Tech","Awesome!"] function changeBGColor() { document.body.bgColor = prompt("What color should the background be?","Put ANY color here!"); checkForTeamColors(); } function changeTXTColor() { document.getElementById("text").style.color = prompt("What color should the text be?","Put ANY color here!"); checkForTeamColors(); } function checkForTeamColors() { var bgcolor = document.body.bgColor var txtcolor = document.getElementById("text").style.color var loopcount = 1 while (loopcount <= 12) { if ( (bgcolor == teamcolors[loopcount] && txtcolor == teamcolors[loopcount + 1]) || (bgcolor == teamcolors[loopcount + 1] && txtcolor == teamcolors[loopcount]) ) { alert("You have picked the team colors of " + teamcolors[loopcount + 2] + ". " + taemcolors[loopcount+3]) } loopcount = loopcount + 4; } } </script> </head> <body> <p id="text" align="center">This text will change color if you want to. <br> Maybe try a certain combination, like Orange and Blue, or Red and Black?<br></p> <button onClick="changeBGColor()">Click me to change the BG Color!</button> <button onclick="changeTXTColor()">Click me to change the text Color!</button> <p id="variables"></p> <script type="text/javascript" document.getElementById("variables").innerHTML = ( bgcolor + " " + txtcolor ) </body> </html> Hi friends i have a gridview with id gvcustomers...it has tow columns latitudes and longitudes i want to loop thoiugh the gridview on the client side and get the values like this...but the problem i have is mentioned in the comments below var theGridView = document.getElementById('<%=gvCustomers.ClientID%>'); for (var rowCount = 1; rowCount < theGridView.rows.length; rowCount++) { /// the numbers in the array are lats and longs which are hard //coded...this where i want the latitude and longitude colmn to come.. var latlongs = new Array(new VELatLong(45, -110), new VELatLong(45, -114), new VELatLong(45, -90), new VELatLong(45, -95)); // } How can i achieve this...thank you akpaga Senior Apprentice Senior Apprentice LTD Bronze - Rating: 3 Posts: 167 Joined: Wed May 27, 2009 4:15 pm Unrated Building a shopping cart, at the moment I have 1 variable array. My JS gets values from hidden inputs when add to shopping cart is clicked. The JS then pushes them all into the array in order. I've managed to get the js code to replace innerHTML and add the array to the HTML to show the products, quantity and totals in a table. However its only showing the last product, price, and total in the array in the table. I need to get it to do this: Product: Quantity: Total: Product1 1 1 Product2 2 2 Product3 3 3 So basically I think I need to have my 3 for statements then plus 2 to each i instead of i++ to print out the products but that still doesn't solve my problem with printing every product in a vertical list, same with quantity and same with total. Heres the code Code: var cart= new Array(); function readInput(){ var prd=document.test.prd.value; var prc=document.test.prc.value; var qty=document.test.amount.value; var total= prc * qty; cart.push( prd ) cart.push( qty ) cart.push( total ); var lenp=cart.length; for(var i = 0; i<lenp-2; i++ ) { document.getElementById("product").innerHTML = cart[i]; } for(var i = 0; i<lenp-1; i++ ) { document.getElementById("qty").innerHTML = cart[i]; } for(var i = 0; i<lenp; i++ ) { document.getElementById("total").innerHTML = cart[i]; } } Code: <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="stylesheet" type="text/css" href="css\basic.css" /> <script language="JavaScript" src="test.js"></script> <title>Shopping Time</title> <body> <form name="test"> <input type="hidden" name="prd" value="Paper"> <p class="desc" value="Paper"> Product: Paper 1</p> <p class="desc"> <input type="hidden" name="prc" value="1.99"> Price: £1.99</p> <p class="desc"> Select Quantity: <select name="amount" onchange="quantity()"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select></p> <p class="submit"> <input type="button" onclick="readInput();" value="Add To Cart" /> </p> </form> <table border="1px solid black" rules="ALL" frame="void" class="cart" width="100%"> <tr> <th> <p class="cart">Product:</p> </th> <th> <p class="cart">QTY:</p> </th> <th> <p class="cart">Total:</p> </th> </tr> <tr> <td class="test"> <div id="product"> <p class="cart">Product:</p> </div> </td> <td> <div id="qty"> <p class="cart">QTY:</p> </div> </td> <td> <div id="total"> <p class="cart">Total:</p> </div> </td> </tr> </table> </body> </html> I like to figure out in my ready made For Loop it out puts a list of names and amounts I want to figure out how to put in a colour scheme. such as having every second row in yellow highlight? here is my code Code: <title>The Lighthouse</title> <link href="lhouse.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="list.js"></script> <script type="text/javascript"> total=0; for (var i=0; i<amount.length; i++) { total=total+amount[i]; } document.write(total); </script> </head> <body> <div id="title"> <img src="logo.jpg" alt="The Lighthouse" /> The Lighthouse<br /> 543 Oak Street<br /> Delphi, KY 89011<br/> (542) 555-7511 </div> <div id="data_list"> <script type="text/javascript"> document.write('<table'+' border="1"'+' rules="row"'+'cellspacing="0">'+'<tr>'+'<th>Date</th>'+'<th>Amount</th>'+'<th>First Name</th>'+'<th>Last Name</th>'+'<th>Address</th>'+'</tr>'); for (var i=0; i<date.length; i++){ document.write('<tr>'+'<td>'+date[i]+'</td>'+'<td>'+amount[i]+'</td>'+'<td>'+firstName[i]+'</td>'+'<td>'+lastName[i]+'</td>'+'</tr>');} </script> </table> </div> Any suggestions on how to add the colour within the loops So this is what I have so far: Code: import java.util.Random; public class lotteryGame { public static void main(String args[]) throws Exception { int n=0; // counter for the amount of times played int t=0; // total amount of winnings int i=0; // number of matches int a; // first guess int b; // second guess int c; // third guess int d; // first number in the lottery int e; // second number in the lottery int f; // third number in the lottery Random rand = new Random(); while (n<100) // play the game for 100 times { a=rand.nextInt(9) + 1; // assign a random number to a b=rand.nextInt(9) + 1; c=rand.nextInt(9) + 1; System.out.println("Lottery Number"+a+b+c); d=rand.nextInt(9) + 1; e=rand.nextInt(9) + 1; f=rand.nextInt(9) + 1; System.out.println("Your guess"+d+e+f); if (a==d){ i=i+1; System.out.println(a+"is a match"); d=d+10; // if a=d then d is taken out of the range (1-9) } else if (a==e){ System.out.println(a+"is a match"); i=i+1; e=e+10; } else if (a==f){ System.out.println(a+"is a match"); i=i+1; f=f+10; } if (b==d){ System.out.println(b+"is a match"); i=i+1; d=d+10; } else if (b==e){ System.out.println(b+"is a match"); i=i+1; e=e+10; } else if (b==f){ System.out.println(b+"is a match"); i=i+1; f=f+10; } if (c==d){ System.out.println(c+"is a match"); i=i+1; d=d+10; } else if (c==e){ System.out.println(c+"is a match"); i=i+1; e=e+10; } else if (c==f){ System.out.println(c+"is a match"); i=i+1; f=f+10; } if (i==3){ if (a==d-10&&b==e-10&&c==f-10){ t=t+10000; System.out.println("You win!!!"); } else{ t=t+1000; System.out.println("You had 3 matches! You win $1000"); } } if (i==2){ t=t+50; System.out.println("You had 2 matches! You win $50"); } if (i==1){ t=t+10; System.out.println("You had 1 match! You win $10"); } } n=n+1; i=0; } } I don't know what is wrong with the program, It compiles fine but when I run it, it never stops. =/ I figure that Code: n=n+1 would be a counter to stop the while loop. Where do I place it so it can count everytime it runs. Or, What do I need to add in order for the program to stop running after 100 times? Thank You. =] |