JavaScript - Canvas, Settimeout, Recursion Problems...
Well, I clearly haven't the experience with javascript to understand why I can't do this:
Code: function bubbleSortKernel(a, b) { if (b < 50) { swap(a, b); draw(); setTimeout("bubbleSortKernel(++a, ++b)", 200); } } where Code: swap(a, b) does just what it says: swaps the two elements in an array, and Code: draw() looks about like this: Code: function draw() { if (ctx != null) { ctx.clearRect(0, 0, width, height); for (var i = 0; i < rectangles.length; i++) { ctx.fillRect(x, rectangles[i][0], rectangles[i][1], rectangles[i][2]); } } } I'm newer to javascript that other things, and this seems perfectly legal to me. I'm looking for someone who knows more that I and can explain what I'm missing. I'm guessing my timeout doesn't really work like I think it does, but I've gotten so frustrated I can't see the forest for the trees. Any help or nudge is greatly appreciated. Thanks! Similar TutorialsHello, Codingforums. I have looked on Google for a solution, done a handful of things, and cannot get my script to draw to the page. Code: <html> <head> <script type="text/javascript" src="imageFuncs.js"></script> <script type="text/javascript"> showImages = function() { var drawingCanvas = document.getElementById("map"); // Check the element is in the DOM and the browser supports canvas if (drawingCanvas.getContext) { var ctx = drawingCanvas.getContext("2d"); var imageSources = new Array("map.jpg"); var images = new Array(); images = loadImages(imageSources); for (var i = 0; i < images.length; i++) { var img = new Image(); img.src = images[i].src; img.onload = function(){ ctx.drawImage(img,0,0,screen.width,screen.height); } } } } </script> </head> <body onload="showImages()"> <canvas id="map">Your browser does not support canvases...</canvas> </body> </html> The problem appears on the ctx.drawImage(img,0,0,screen.width,screen.height); line. I read that the drawImage method will not draw the image if the images are not loaded, which is why I tried an onload event for img. When I run the code the way it is now, I get a attempt to run compile-and-go script on a cleared scope error from Firebug. When I remove the onload event, the script runs without errors. Either way, no image is drawn on the page. Any help? If it helps, this is the loadImages function that I used to get the array of loaded image objects: Code: function loadImages(sources){ var images = new Array(); var loadedImages = 0; var numImages = 0; for (var src in sources) { numImages++; } for (var src in sources) { images[src] = new Image(); images[src].src = sources[src]; } return images; } I am using this: http://www.crowdsavings.com/open-source/drawbox (http://page-test.co.uk/jquery.drawbox.js is the main JS file). It works fine on desktop browsers, but there is an issue on every Touch mobile phone I have tried. When you draw on the canvas and then go to click a button off the canvas, it doesn't work. You need to touch off the canvas and then the button. So using the demo above, if you draw on the canvas and then click the 'Clear Canvas' button, it doesn't work and you have to press it again. I have tried setting focus on the body and also detecting what the focus is when a touch action is performed, but no luck. I know the entire screen is responsive to touch and mouse events, where I would have thought it best to just make the canvas section respond to touch/mouse events. this code: Code: $(document).ready(function() { $('body').click(function(evt) { if(evt.target.nodeName === 'A' && $(evt.target).hasClass('cross-link')) { $('a[href=#2]').trigger('click'); } });}); gives me and error of "too much recursion" how can i solve this? hello every one , i'm new and i hoped u could help me with my code I keep getting the same message "too much recursion" and i really don't know what is wrong , my friend and i codded the same way ,but it works for her not for me , here is the code : [merge sort algorithm] Code: var A=[2,999,45,23,17,879]; var B=[]; var C=[]; var i; var j; var k; var x=0; var mergesort_counter=0; var merge_counter=0; mergesort(A); //========================================================= //document.write( "<h2>mergesort</h2><p>", A, "</p>" ); function mergesort(A){ var n=A.length; mergesort_counter++; //count mergesort calls document.write( "<h2>mergesort</h2><p>", A, "</p>" ); var mid=Math.floor(n/2); if (n>1){ for (i=0;i<mid;i++){ B[i]=A[i];} for(j=mid;j<n;j++){ C[x]=A[j]; x++;} mergesort(B); mergesort(C); merge(B,C,A);} else document.write("the list is too short ");} function merge(B,C,A){ merge_counter++; //count merge calls i=0;k=0;j=0; while( i<B.length && j<C.length ){ if (B[i]<=C[j]){ A[k]=B[i]; i++;} else{ A[k]=C[j]; j++;}k++;} if(i==B.length) for (var l=j; l<C.length ; l++) {A[k]=C[l]; k++;} else for (var l=i; l<B.length ; l++) {A[k]=B[l]; k++;} document.write( "<h3>merge</h3><p>", A, "</p>" )} Hey im having a problem recursively calling my function. What I want to do is to change MyImages[0-14] with a timeout between them. Here is my code. Code: function swapImage(i) { if(i < 15) { MyImages[i].src = "red_dot.gif"; setTimeout("swapImage(i+1)",500); } } The problem is that it will only change MyImages[0] and MyImages[1] Hi, can anyone tell me... Code: function Obj() { this.recursiveMethod=function () { //...how to invoke Obj.recursiveMethod from here? } } Gus Code: function checkifischild(draggedElement,destination) { $getid = $("#" + destination).attr("class"); var __temp = $getid.split(' '); console.log(__temp) for(i = 0;i < __temp.length; i++){//for the length of the classes if(__temp[i].match("child-of-")) {//check if its a child parent = __temp[i].substring(9);//get the parents node if(draggedElement == parent) { console.log('yes'); return false; } } } checkifischild(draggedElement,parent) } i have the following function basically what it does it gets 2 parameters node-23,node-17 for example it finds the classes of node-17 and splits them up ["child-of-node-16", "initialized", "ui-droppable", "expanded"] ["child-of-node-19", "initialized", "parent", "expanded", "ui-droppable"] ["child-of-node-23", "initialized", "parent", "expanded", "ui-droppable"] so i compare each time the first parameter along with the substring of the child-of and if they are the same its returns false now my problem is if i call the function just like this checkifischild(node-23,node-17) it works i get in the console yes for example if i do this tho if(checkifischild(node-23,node-17) == false) it fails :? any ideas will be appreciated thxxx Hello I am trying to create a family tree, parents / grandparents etc, of a single person... My database etc is already working but I cannot find any working examples that I can make sense of... Each of my records has a name, dob and id of each parent.... How can I get X generations from this.. I thought something like this might work.. GetParents For each parent GetParents And so on... But I have no idea how to put this into code... Any suggestions to put me on the right line would be greatly appreciated Thanks Hi, I am having trouble with a recursive function I created to list out the indexes and values of various nested objects. Code: var macros={ CTRL: { ALT: { ENTER: "<br />", P: "<p>.</p>", A: "<a href=\"\">.</a>", _1: "<h1>.</h1>", _2: "<h2>.</h2>", _3: "<h3>.</h3>", _4: "<h4>.</h4>", _5: "<h5>.</h5>", _6: "<h6>.</h6>" } } }; I want to print out the whole 'bread crumb trail' to each object, ie CTRL ALT 6: <h6>.</h6>, but at the moment my function prints out CTRL ALT twice for 'ENTER' and then never again. The function: Code: function printObj(obj) { for(i in obj) { var n=i.replace("_", ""); document.write(n); if(typeof obj[i]=="string") { document.write(":"); document.write(" "+obj[i].replace(/</g, "<").replace(/>/g, ">")); } else { document.write(n); } if(typeof obj[i]=="object") printObj(obj[i]); document.write("\n"); } } printObj(macros); The current output: Code: CTRLCTRLALTALTENTER: <br /> P: <p>.</p> A: <a href="">.</a> 1: <h1>.</h1> 2: <h2>.</h2> 3: <h3>.</h3> 4: <h4>.</h4> 5: <h5>.</h5> 6: <h6>.</h6> Any advice would be appreciated. Cheers, Gus well, when i do this fucntion: function scroll(){ window.scroll(0,60) } i get a javascript error: Error: too much recursion well, what is wrong? what does that mean? how do i fix it? thanks for any help Is there another JS function that I can use to force a time delay without having the code continue to run? I'm using the setTimeout() function but the call to this function doesn't stop the code flow. I need to stop the code flow while waiting. I guess I need a Sleep() type of JS function. What I'm trying to do is display some blank text on the screen using a for loop (I'm using <BR> to give the appearance of "opening up" a vertical window section in the browser) and I need this 'text' to complete before allowing the following code in the function to execute. The following code will display a Table with rows of data. I'm trying to use a timing function to give a visual impression of a window opening up just before the data displays. Thanks... Okay, for some reason the setTimeout isn't working for me, and I have no idea why. I've tried everything and Googled even more. If anyone has any ideas, I'll be grateful Code: function display(min,sec) { if (sec <= 0) { sec=60; min-=1; } if (min <= -1) { sec=0; min=0; tEnd(); } else { sec = sec-1; } if (sec<=9) { sec = "0" +sec; } document.form.time.value=min+":"+sec; SM = window.setTimeout("display("+min+","+sec+")",1000); } function tEnd() { window.clearTimeout(SM); alert('Your time is up!'); } Thanks in advance. Hello - I've got this lovely little animation that slides some div fields to the right a short distance. Everything works except the setTimeout (located in the SlideIn function). It simply 'jumps' without taking any time at all. I've tried a bunch of stuff: changed the amount of time from 100 to 10000 changed it from var t = setTimeout("SlideIn()", 1000) SlideIn with/without the brackets, with/without the quotation marks. SlideIn() SlideIn(i) SlideIn(label_id_fixed) SlideIn(label_id_no) Just about at the end of my rope, and so many different combinations I'm forgetting which ones I've tried and which I haven't. I know it is looping through because it gets to the end position and allows the other JavaScript functions to work ok. So it is not getting 'stuck' or anything like that. Here is the complete code (there is a style sheet located separately). Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="class.css" /> </head> <script type="text/javascript"> //<![CDATA[ window.onload=starter; function starter(){ collapseMenu(); SetUpAnimation(); } function SetUpAnimation(){ if (document.querySelectorAll) { labels = document.querySelectorAll('div.label'); } else if (document.getElementsByClassName) { labels = document.getElementsByClassName('label'); } //loops through the labels if (labels){ for (var i=1; i <= labels.length; i++) {SlideIn(i); } } } function SlideIn(label_id_no){ var label_id_fixed = label_id_no; var endPos = 150; var currentPos = 0; for (currentPos = 1; currentPos < 60; currentPos++){ var label_id_name = "label" + label_id_fixed; document.getElementById(label_id_name).style.left = currentPos + "px"; setTimeout("SlideIn", 1000); } } function collapseMenu(){ var elems = null; var labels = null; if (document.querySelectorAll) { elems = document.querySelectorAll('div.elements'); labels = document.querySelectorAll('div.label'); } else if (document.getElementsByClassName) { elems = document.getElementsByClassName('elements'); labels = document.getElementsByClassName('label'); } if (elems){ for (var i=0; i < elems.length; i++) { elems[i].style.display="none"; } for (var i=0; i < labels.length; i++) { labels[i].onclick=showBlock; } } } function showBlock(evnt){ var theEvent = evnt ? evnt : window.event; var theSrc = theEvent.target ? theEvent.target: theEvent.srcElement; var itemId = "elements" + theSrc.id.substr(5,1); var item = document.getElementById(itemId); if (item.style.display=='none'){ item.style.display='block'; }else{ item.style.display='none'; } } //]]> </script> </head> <body> <div class="label" id="label1">this is a label</div> <div class="elements" id="elements1"> <p>painting</p><br /> <p>photography</p><br /> </div> <div class="label" id="label2">this is another label</div> <div class="elements" id="elements2"> <p>sculpture</p><br /> <p>ceramics</p><br /> </div> </body> </html> Hi trying to load a random swf files using setTimeout please help Code: </head><script type="text/javascript"> var numberOfSongs = 3 var sound = new Array(numberOfSongs+1) sound[1]= "number/1.mp3" sound[2]= "number/2.mp3" sound[3]= "number/3.mp3" function randomNumber(){ var randomLooper = -1 while (randomLooper < 0 || randomLooper > numberOfSongs || isNaN(randomLooper)){ randomLooper = parseInt(Math.random()*(numberOfSongs+1)) } return randomLooper } var randomsub = randomNumber() var soundFile = sound[randomsub] document.write ('<EMBED src= "' + soundFile + '" hidden=true autostart=true loop=false>') setTimeout(randomNumber,4000); </script> <body onload="randomNumber()"> Hello guys I need to get something fun! with setTimeout function! I am n00b! so be patent please. I need when <body onload="Myfunc();"> fires, that function should show "Please wait...!" or "Loading...". for , say 5 seconds!. then it disappear. I used setTimeout with that but it didn't do what I wanted! here is my code: PHP Code: function Myfunc(){ document.getElementById("ss2").innerHTML = "Loading..."; setTimeout("Myfunc();", 5000); } // where id="ss2" is the place to display the string "loading..." ! and a one more question ! can I do something like a while loop! where it holds *i* value as seconds! and for every second it passes it should print out a string I make it up ! let say loop for 3 seconds ! So, when seconds = 0 then display "string of second 0" and stick it in there, then go to the next second when it is exactly = 1 then display "new line with string of second 1" and stick it in there, then do to the last second when it is exactly = 2 then display " new line with string of second 2" and stick it in there, exit the loop! is there anyway to do that? please note that I am a n00bie ! help is much appreciated ! Code: function funt() { var link = document.getElementsByClassName("class")[0]; if(link != null) { var i = 0; if(check != link.childNodes[i]) { link.childNodes[i].click(); check = link.childNodes[i]; } else { window.location = "website" } } else { if(document.getElementById('enbut').value != "some value") { document.getElementById('id').click(); } window.location = "website" } t=setTimeout("funt()",3000); } with this i'm trying to get it to loop every 3 seconds using the settimeout function at the end of the loop. each time i run this it just runs once and exits. anyone know what i'm doing wrong? Hi all, I've noticed that setTimeout seems to return a simple integer as it's "id" which can be used to clear the timeout ahead of time. So, in order to have multiple setTimeouts called (which requires the previous one to be cleared before the next one is called), I simply did this: Code: clearTimeout(setTimeout(function() { /* some code */ }, 1000) -1); Note the "-1"... each time this code is called, it starts a new setTimeout and clears "instance-1" which is supposed to be the previous instance. The idea is that this block can be called hundreds of times, and when the calling finally stops, the inner code is executed 1 second later. This SEEMS to be working (yes, even in MSIE!). Question is, am I fooling myself? Is this wrong? If so, what's the right way to do it? Thanks... -- Roger (btw, the actual use of this is dynamic resizing of a DIV by dragging the corner with the mouse.... I want the actual PX size to display live while resizing, then after resizing stops, the size display goes away 1 second later... in case you were wondering). I'm trying to set a timer when someone moves off of an image. When I try my event without the timer there are no problems but it throws syntax or object expected errors (if I play with the quotes some) when I add in the timer. This is inline code on the image. onMouseout="newsTimer = setTimeout("Effect.toggle('news', 'slide')", 500)"; It is likely something simple I am overlooking but I cannot find any answers after a long search. Thank you for any and all help. Hi there The JavaScript below behaves erratically - sometimes the timing is perfect, at other times it show 20 mins has passed when only 6 has in reallity - quite some gain - I'm baffled! Code: Public Function SessionTime(ByVal DivName As Panel) As String Dim vTime As String = "var sessionTimeout = 19; " & vbCr vTime += "function ReadCookie(cookieName) " & vbCr vTime += "{ " & vbCr vTime += "var theCookie=""""+document.cookie; var ind=theCookie.indexOf(cookieName); " & vbCr vTime += "if (ind==-1 || cookieName=="""") return """";" & vbCr vTime += "var ind1=theCookie.indexOf(';',ind); " & vbCr vTime += "if (ind1==-1) ind1=theCookie.length; " & vbCr vTime += "return unescape(theCookie.substring(ind+cookieName.length+1,ind1));" & vbCr vTime += "} " & vbCr vTime += "function DisplaySessionTimeout()" & vbCr vTime += "{ " & vbCr 'assigning minutes left to session timeout to Label vTime += "if (sessionTimeout > 1) " & vbCr vTime += "{ " & vbCr vTime += "document.getElementById('" & DivName.ClientID & "').innerText = sessionTimeout + "" Minutes remaining until session timeout!""; " & vbCr vTime += "} " & vbCr vTime += "else " & vbCr vTime += "{ " & vbCr vTime += "document.getElementById('" & DivName.ClientID & "').innerText = ""ONLY ONE MINUTE REMAINS UNTIL SESSION TIMEOUT!""; " & vbCr vTime += "}" & vbCr vTime += "sessionTimeout = sessionTimeout - 1; " & vbCr vTime += "var Posted = ReadCookie('PostedValue'); " & vbCr vTime += "if (Posted == 0)" & vbCr vTime += "{ " & vbCr vTime += "sessionTimeout = 19; " & vbCr vTime += "var expires = new Date(); " & vbCr vTime += "expires.setUTCFullYear(expires.getUTCFullYear() + 1); " & vbCr vTime += "document.cookie = 'PostedValue=1; expires=' + expires.toUTCString() + '; path=/'; " & vbCr vTime += "}" & vbCr 'if session is under preset warning vTime += "if (sessionTimeout > 5) " & vbCr '<--------------- 4 vTime += "{ " & vbCr vTime += "document.getElementById('" & DivName.ClientID & "').style.visibility=""hidden""; " & vbCr vTime += "}" & vbCr vTime += "else " & vbCr vTime += "{" & vbCr vTime += "document.getElementById('" & DivName.ClientID & "').style.visibility=""visible""; " & vbCr vTime += "}" & vbCr 'if session is not less than 0 vTime += "if (sessionTimeout >= 1) " & vbCr 'call the function again after 1 minute delay vTime += "{ " & vbCr vTime += "setTimeout('DisplaySessionTimeout()', 60000); " & vbCr '<------60000 vTime += "} " & vbCr vTime += "else " & vbCr vTime += "{ " & vbCr 'show message box vTime += "alert(""Your current Session will expire in approx one minute""); " & vbCr vTime += "} " & vbCr 'vTime += "alert(""Set to "" + ReadCookie('PostedValue')); " & vbCr vTime += "} " & vbCr vTime += "DisplaySessionTimeout();" & vbCr Return vTime End Function I'm trying to delay this line by 1 second, but can't seem to figure out the syntax. Code: window.location.href="index.php?vid_id="+<?php echo $vid_id +1 ?>; this is the entire function Code: $('#cancel').click(function() { $.ajax({ type: "POST", url: "scripts/greenlight.php?vid_id="+<?php echo $vid_id ?>, data: "vote=2", success: function(){ }}); document.getElementById("greenlight").src="img/greenlight_btns/greenlight_btn.png"; document.getElementById("cancel").src="img/greenlight_btns/cancel_btnOver.png"; //window.location.href="index.php?vid_id="+<?php echo $vid_id +1 ?> window.setTimeout(function() { window.location.href="index.php?vid_id="+<?php echo $vid_id +1 ?>; }, 500); }); // end click |