JavaScript - Nested Timeouts - How To Implement?
I'm running into issues while trying to make some simple code to loop through and display different combinations of 3 colours.
I want to show 3 boxes on screen and then loop through/increment each possible combination of colours. For simplicity's sake I'm trying to go from black to white in each box like this: (box1rgb/box2rgb/box3rgb) step 1: 000 000 000 step 2: 000 000 111 step 3: 000 000 222 . . . step 256: 000 000 255255255 step 257: 000 111 000 step 258: 000 111 111 step 259: 000 111 222 . . . step 512: 000 111 255255255 step 513: 000 222 000 step 514: 000 222 111 . etc. Yes, I know the thing will take a long time to complete! The colour is being set by the statement document.getElementById("box#").style.backgroundColor = "rgb(" + p1 + "," + p1 + "," + p1 + ")"; where p1 is the incrementing variable. Firstly I tried to do it using nested "for" loops. Code: for (p3=0;p3<=255;p3++) { document.getElementById("box03").style.backgroundColor = "rgb(" + p3 + "," + p3 + "," + p3 + ")"; for (p2=0;p2<=255;p2++) { document.getElementById("box02").style.backgroundColor = "rgb(" + p2 + "," + p2 + "," + p2 + ")"; for (p1=0;p1<=255;p1++) { document.getElementById("box01").style.backgroundColor = "rgb(" + p1 + "," + p1 + "," + p1 + ")"; } } } But of course the code executes far too rapidly for each combination to be seen. It all chewed up lots of CPU and nothing was smooth. To slow the process, I tried a single recursive loop using a timeout statement: Code: function loopandshow() { document.getElementById("box01").style.backgroundColor = "rgb(" + currentcolour + "," + currentcolour + "," + currentcolour + ")"; currentcolour += 1; if (currentcolour <= 255) window.setTimeout("loopandshow();", 20); } This worked smoothly for a single box but I couldn't work out how to nest this format 3 levels deep and have each level increment only when the deeper level had completed the cycle. Any advice would be gratefully appreciated. Thanks in advance. Similar TutorialsIs there a simple way to cancel all active timeouts without the need to reference each one individually ?
I don't know how to work with timeouts. I have a simple blinking image. but I'm not sure how to set multiple timeouts? Basically I want the image to blink to another one for 400, then return to the first image for 5000 here's the basic starting point I have: Code: <script type="text/javascript"> var img_off = new Image(); img_off.src = 'images/blink.png'; var img_on = new Image(); img_on.src = 'images/orho2.png'; function blink() { var e = document.getElementById("blinking_orho"); e.src = (e.src == img_on.src) ? img_off.src : img_on.src; setTimeout("blink();", 5000,); } </script> I have a parent checkbox that when checked, I want it to validate whether 1 of the four child checkboxes are selected. I've gotten it to work but I'd like to have one if condition as opposed to all the '&&'. Anyone know how to clean these up? Code: <script type="text/javascript"> function checkMe() { var mbe = document.getElementById('a10_Class01'); if (mbe.checked) { for (i=0; i<4; i++){ if (document.getElementById('a10_ClassSub1').checked == false && document.getElementById('a10_ClassSub2').checked == false && document.getElementById('a10_ClassSub3').checked == false && document.getElementById('a10_ClassSub4').checked == false){ alert('Choose a minority.'); return false; } } } } </script> I am trying to code a piece of JavaScript that queries the Internic for whois information (using either a domain or an IP address) and puts the results into a JSON object with separate fields for each piece of information.
Hi everybody, I have written a javascript slideshow with pause-play-next-previous buttons, but the images are too many and users have to wait too long especially with slower connections - i wonder if anybody can suggest a way to implement the script with fast preloading of the first few images, increment preloading or a similar trick. I will copy my code below but i also copy first this link: http://www.javascriptkit.com/script/...entslide.shtml which is an example of increment loading slideshow working fine! my problem is i am quite new to javascript and i wouldnt know how to customize it in order to take away the link function, that i dont need, and add captions and buttons etc. Any advice in one of the two directions (working on my own script below or customizing the linked one above) would be very very appreciated! Also alternative ideas (i.e. some solutions using pure CSS) are welcome! I do know some jquery plugin could do but i am trying to go more into the code, even though i still need a lot of advices and tutorials, the goal is solving this specific problem but also learning! Thx a lot in advance. Here my code (just 2 images here in the list to make it shorter for you, the complete list is more than 50 pics!): Code: <script language="JavaScript"> <!-- var interval = 8000; var random_display = 0; var imageDir = "portraits/"; var imageNum = 0; didascalieArray = new Array(); imageArray = new Array(); didascalieArray[imageNum] = "caption1"; imageArray[imageNum++] = new imageItem(imageDir + "image1.jpg"); didascalieArray[imageNum] = "caption2"; imageArray[imageNum++] = new imageItem(imageDir + "image2.jpg"); var totalImages = imageArray.length; function imageItem(image_location) { this.image_item = new Image(); this.image_item.src = image_location; } function get_ImageItemLocation(imageObj) { return(imageObj.image_item.src) } function getNextImage() { if (random_display) { imageNum = randNum(0, totalImages-1); } else { imageNum = (imageNum+1) % totalImages; } var new_image = get_ImageItemLocation(imageArray [imageNum]); document.getElementById("didascalia").innerHTML = didascalieArray[imageNum]; return(new_image); } function getPrevImage() { if(imageNum-1 < 0) { imageNum = totalImages-1; } else imageNum = (imageNum-1) % totalImages; var new_image = get_ImageItemLocation(imageArray [imageNum]); document.getElementById("didascalia").innerHTML = didascalieArray[imageNum]; return(new_image); } function prevImage(place) { var new_image = getPrevImage(); document[place].src = new_image; } function switchImage(place) { var new_image = getNextImage(); document[place].src = new_image; var recur_call = "switchImage('"+place+"')"; timerID = setTimeout(recur_call, interval); } // --> </script> I have a main window which produces a number of child windows when I press a button. Users need to be able to switch between windows using Ctrl+Tab hot key. I was trying to implement this by intercepting keyup/keydown events in one of the frames. But the problem is that main window has several frames and I don't have access to all of them because some of them are in different domains. As soon as a user clicks on a frame without my handler the hot key is not working anymore. Any ideas how to implement it? Maybe an ActiveX component? If ActiveX could help me - how does it work? Are there any tutorials or examples how to write an activeX to intercepts hot keys in IE? Thank you. Friends i'm in a dire situation only have wednesday to submit ..so heres the problem....i have a course work assigment where i have to hardwire Hardware items and their item codes description and prices and ask the user to input their name address the itemCode and quantity nad then creat an invoice which looks like this HARDWARE ITEMS CODE DESCRIPTION UNIT PRICE K16 Wood screws, brass, 20mm, pack of 50 $ 7.75 D24 Wood glue, clear, 1 litre $ 5.50 M93 Sandpaper, medium grade, 100 sheets $10.25 M94 Sandpaper, fine grade, 100 sheets $14.75 PLACE YOUR ORDER! NAME: Bill Silic ADDRESS-1: Apt 23 ADDRESS-2: Building 8 ADDRESS-3: Winchester POST CODE: 89763 ENTER CODE (XX to Stop): CODE: D24 QUANTITY: 2 CODE: K16 QUANTITY: 1 CODE:XX INVOICE FOR ORDER Bill Silic Apt 23 Building 8 Winchester POST CODE: 89763 D24 Wood glue, clear, 1 litre 2 @ $ 5.50 $ 11.00 K16 Wood screws, brass, 20mm, pack of 50 1 @ $ 7.75 $ 7.75 TOTAL: $ 18.75 Shipping: 2 items @ 1.00 2.00 TOTAL INCL. SHIPPING: 20.75 VAT at 20% 4.15 TOTAL TO PAY: 24.90 I HAVE ALREADY COMPLETED THIS BY MYSELF AND GOT IT WORKING WITH NO PROBLEM ..But my problem is that the teacher wants us to TEST FOR NULL ENTRY meaning if the user enters the wrong Itemcode or no ItemCode at all and give an sensible output for that case ..... she wants us to put it in a method after main and then call it in main using a do while loop so my method looks something like this Code: public static boolean isSomethingCorrect(String itemCode){ if(itemCode.equals("")||itemCode.equals(null)){ System.out.println("A sensible output"); return true; }//close if return false; } } // and i have to implement it where i ask the user for input using a Do while loop in this area Code: //a do while loop to test null code entry do{ System.out.println("Please select a code from the list"); String itemCode= br.readLine(); System.out.println("Please enter quantity of items " +itemCode); String itemQuantity= br.readLine(); int quantity= Integer.parseInt(itemQuantity); // I Will be forever grateful for any help on this program because i have tryed for hours upon hours and i just cant get it and i need to submit the day after tomorrow We are using Volusion for our shopping cart, but I am trying to put a pop-up option in there for marketing. Volusion operates using a template.htm and css files that I can access, and of course I cannot access the root file (default/index.htm). The program I am tyring to use says to place the following line next to the <body> tag of the default page: <!-- POPUP --><script src=http://www.metalcloak.com/v/34.popup/script.js></script><!-- END --> 34.popup is a folder with the applicable script and graphics. For whatever reason, if I put this line in the template file after this location: <body id="body" onload="if(typeof(store_init)=='function')store_init(event);" > It does not function. Talking with the techies at Volusion, they have no recommendation other than using JavaScript to point this script to operate on the home page only. Any help or direction of what I should do (even if it means scrapping a pre-packaged Popup Proogram as an option) is much appreciated. Thank you. Hi, I got this two javascripts: - Datepicker by Jason Moon (http://calendar.moonscript.com/dateinput.cfm) which can have multiple of this datepicker on a single form - Dynamic Add/Remove rows from http://viralpatel.net/blogs/2009/03/...avascript.html I would like to add rows of fields with each rows having it's individual datepicker. Code: <table id="billcmp_7" width="320" border="0"> <tr> <td width="200" align="center"><script>DateInput('billcmp7_cycle', true)</script></td> <td width="10"> </td> <td width="100" align="center"><input name="billcmp7_name" type="text" /></td> <td width="10"><INPUT type="checkbox" name="chk"/></td> </tr> </table> <table width="320" border="0"> <tr> <td colspan="4" align="center"><INPUT type="button" value="Add Row" onclick="addRow('billcmp_7')" /><INPUT type="button" value="Delete Row" onclick="deleteRow('billcmp_7')" /></td> </tr> </table> I just want this section Code: <script>DateInput('billcmp7_cycle', true)</script> to work like Code: <script>DateInput('billcmp7_cycle_1', false)</script> <script>DateInput('billcmp7_cycle_2', false)</script> when click on the add button. Here's what i meant? Link cant get the time to be different as it is still read as single datepicker. Any1 has any idea how or any alternative? I have implemented timer for 10sec.It's displaying the message.Now After pressing OK button that is after first 10 sec I want the timer to restart again and run for 20 secs and then display other message.After pressing OK button,that is for 20 secs I want the timer to restart again for 60 secs and display a new third message. Here is my code: Can you help me? =========================================================== <SCRIPT LANGUAGE = "JavaScript"> <!-- var secs var timerID = null var timerRunning = false var delay = 1000 function InitializeTimer() { // Set the length of the timer, in seconds if(secs = 10) { StopTheClock() StartTheTimer() secs++ } else if(secs = 15) { StopTheClock() StartTheTimer() } } function StopTheClock() { if(timerRunning) clearTimeout(timerID) timerRunning = false } function StartTheTimer() { if (secs==0) { StopTheClock() // Here's where you put something useful that's // supposed to happen after the allotted time. // For example, you could display a message: alert("Would You Like to try again?") } else { self.status = secs secs = secs - 1 timerRunning = true timerID = self.setTimeout("StartTheTimer()", delay) } } //--> </SCRIPT> Here is how I'm calling it: <FORM> <INPUT TYPE=BUTTON VALUE="Submit" onClick = "InitializeTimer()"> </FORM> Please help! Can anyone give me some advice on how to manipulate Google Fusion Table using Javascript??? I've read the Fusion table's Developer Guider. But still feel confused. Can anyone tell me the specific solution?? Or give me a sample code?? Thanks very much!!!!!! Hi. I'm working on a script that picks out a random entry in an array every 10seconds and show it to the user (using document.write). So far I've got the "Randomizer" to work like this: Code: function random(){ var nummer = Math.floor(Math.random()* tekst.length); return nummer; } var tekst = new Array("Different", "Values"); and showing it like this: Code: document.write(tekst[random()]); Now, I've tried my best to implement setInterval() to give me a new random number every 10seconds, but so far without any luck... I appreciate all help! Thx in advance. I'm trying to reuse some code in a different context to do a different job. The code to be reused contains hundreds of lines similar to a = new b.c.d(e,f) with different value for e and f. I need to create a new user defined object with the structure b.c.d. I've made numerous attempts along the lines of: Code: function d (e, f) { this.e = e; this.f = f; } function c () { this.d = d (e, f); } function b () { this.c = c; } var a = new b.c.d("test", "message"); with various permuations of functional declarations. However I get error message "Object expected" or "b.c.d is null or not an object" at the final line of the example. It works with the test line var a = new d("test", "message") but not when I start to build up the expression. How should I define of b.c.d? OK i'm trying to make an affiliate section for my page in javascript, I used double arrays and it's terribly coded. Please help. I'm new to this... Code: <html> <body> <script type="text/javascript"> var alley = new Array(); alley[0] = new Array( "http://stereo.b1.jcink.com/", "http://i49.tinypic.com/5klkb6.gif", "Stereo Wired" ); alley[1] = new Array ( "http://s1.zetaboards.com/N2010/", "http://sixpop.com/files/246/n2010.png", "N2010" ); alley[2] = new Array ( "http://theipodnation.net", "http://img15.imageshack.us/img15/1043/affiipod.png", "The Ipod Nation" ); for ( i = 3; i < alley.length; i++ ) { for ( m = 0; m < alley[i].length; m++ ) { document.write(" <a href='" + alley[i][m][0] + "'><img src='" + alley[i][m][1] + "' alt='" + alley[i][m][2] + "' /></a> ") } } </script> </body> </html> This may be a basic programing problem but I am writing a function to validate a form using a bunch of else-if statements and encounters a problem when I use nested if/else-if statements. It will not continue on to the next else-if, after it returns false. Code: // to check each entry on the form and alert user if entry is invalid. function checkform(){ var checkssn = /(\d{3})-(\d{2})-(\d{4})/; var checkphone = /(\d{3})-(\d{4})/; var checkname = /[a-zA-Z]+(\.|,|\s)*/; var checkzip = /(^967|^968)\d{2}(-\d{4})?$/; // check to see if user have selected an Election if (!document.f1.elections[0].checked && !document.f1.elections[1].checked && !document.f1.elections[2].checked && !document.f1.elections[3].checked) { window.alert("Please select an Election!") return false; // check to see if user entered a valid SSN } else if ( checkssn.test(document.f1.ssn.value) == false){ window.alert("[1]. Please enter a valid social security number in the format ddd-dd-ddd"); return false; // check to see if user entered a valid home telephone number or business telephone number }else if ( document.f1.home_phone.value == '' && document.f1.business_phone.value == '') { window.alert("[4]. Please enter a Home or Business telephone number!") return false; } else if ( document.f1.home_phone.value != ''){ if (checkphone.test(document.f1.home_phone.value) == false){ window.alert("[4]. Please enter a valid home phone number in the format ddd-ddd"); return false; } } else if ( document.f1.business_phone.value != ''){ if ( checkphone.test(document.f1.business_phone.value) == false){ window.alert("[4]. Please enter a valid business phone number in the format ddd-ddd"); return false; } // check to see if user entered a valid Name }else if ( checkname.test(document.f1.lastname.value) == false){ window.alert("[5]. Last Name can only consist of letters, periods(.), commas(,) and spaces"); return false; }else if ( checkname.test(document.f1.firstname.value) == false){ window.alert("[5]. First Name can only consist of letters, periods(.), commas(,) and spaces"); return false; The problem occurs when it validates the phone numbers. When a valid number is entered, it will not move to the next else-if statement to validate the name. It's been years since I program in Java/C, so I'm a bit rusty. Any help is appreciated. -Alex Hello. I was wondering if there is a way to call a second Javascript function from within the first. For example: <script>...call first function...</script> Inside first function: If (a==1) <script>...call second function...</script> else (a==2) <script>...call third function...</script> My thinking as to why I would need this is because I need to access two different Google Maps API codes. If that isn't possible, does anyone have any other suggestions? Hey Guys, I'm currently a seasoned programmer who is in a programming class at my school. We're currently learning advanced JavaScript, and we're on the topic of nested loops. After teaching us about for and while loops, my teacher gave us a little puzzle to solve. It's kind of difficult to explain, but I'll give you guys my current code and what it outputs. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Word Reversal</title> <script type="text/javascript"> var ask = prompt("How many words do you want?",""); while (ask < "1") { alert("You have to have at least one word!"); var ask = prompt("How many words do you want?",""); } var num = parseInt(ask) + 1; var final = ""; for (var i=1; i < num; i++) { var word = prompt("What's word " + i + "?"); final = final + "Word " + i +": " + word + "<br/>"; } </script> </head> <body> <script type="text/javascript"> document.writeln(final); </script> </body> </html> The current output, when the user wants two words, and word 1 is one and word 2 is two, comes out to be: Code: Word 1: one Word 2: two Which is great, but the only problem is, this is what the output's supposed to be: Code: Word 2: two Word 1: one I'm stumped. I've had numerous programming challenges in my life which I've solved, but I'm not sure where to go next on this one. The script is supposed to use a nested loop, but what goes in what loop to reverse the order of the user's input? I asked my teacher for help, but he told me "Ask someone else." I asked another seasoned programmer in my class, who was just about as stumped as I was, so I went back to my teacher. "Well, ask another person" he replied. And can you believe this guy has a Master's Degree of Computer Science? So I'm asking you guys: the community. I hope someone will be able to help me. On top of that, I have to help and tutor two special education students in my class on this kind of stuff during class, and they can't get the project done until I get it done, as they learn from analyzing and copying my work (which my teacher told me to do). They get upset when they have nothing to code, and they end up goofing off the entire period, or using it as a study hall. I need to get them back on track, so we can move on to the next project. Please help me with this code - it would be greatly appreciated. Thank you! Hello codingforums.com! Right, this is probably going but such a stupid newbie thread but here goes.. I've finally got myself into gear to start learning javascript. I've been watching video tutorials, learning from websites and simply learning by error. I understand the concept of for loops, but the whole nested thing doesn't seem to click for some reason. I thought i understood and managed to write a piece of code that constantly writes '*' across the screen. Could someone with some pretty damn good knowledge of javascript be able to walk me through step by step of my script to explain what actually is happening? It would help loads. here is the script, many thanks!! <script type="text/javascript"> var counter = 0; function writeStars(){ for(i=0;i<1;i++){ for(a=0;a<=counter;a++){ document.write("*"); } counter++ document.write("<br />"); } } setInterval("writeStars()", 200); </script> Hi I need help to finish this code with using nested if statements A price of a ticket to a passenger will be: First Class 500 Economy Class (with meal) 400 Economy Class (without meal) 200 How I can write a JavaScript code according to the following specifications: a. Read the class that the passenger wants to travel on. b. If the class is the first class, print the price of ticket. c. If the class is the economy class, ask the user if he/she wants a meal on the flight. Then print the price of the ticket according to the response of the passenger. The program should simply accept one possible strings the user enters; it is not required to work for all possible inputs such as First, first, FIRST or Yes , yes, YES. This is the code which I have been trying { var inputNum = prompt("Enter the class you want\n first class?\neconomy? :"); if (isNaN(inputNum)) { if (inputNum.match(/first class/)) { document.write("<h1><center>your Ticket is 500<\center><\h1>"); } else { prompt("<h1>if you want a meal on the flight press OK <\h1>"); document.write("<h1>your ticket is 400<h1>,"); } } After struggling with this for the past 2 days, I've decided it is time to seek out some help. The program is a calculator to show the monthly payments required depending on if the terms are for 2, 3, 4, or 5 year financing. I have the following 4 variables that I need to be placed in the inner loop, but not sure how to do it. pay24, pay36, pay48, pay60 The following loop creates a 4 row x 2 column table which I need it to do, but the inner loop needs to show the value of the 4 variables above. Can someone assist me in this problem? Code: for ( var i=24; i<=60; i+=12 ) { document.write("<tr>"); document.write("<td align=center>" + i + "</td>"); for ( var j = 2; j <= 2; j++ ) { document.write("<td align=right>" + j + "</td>"); } document.write("</tr>"); } |