JavaScript - Fail To Catch Exception When Using Setinterval
If you try some codes and then catch exception, it should catch the exception when there is. However, if there is a setInterval method in the try clause, then the exception cannot be caught... why???
the following works ( a usual method is invoked in the try clause): Code: <script language="javascript" type="text/javascript"> function invoke() { var i=0; return i.x.y; } try { alert(invoke()); } catch(ex){ alert(ex); } //Any Exception will be caught. </script> if the highlighted line is changed as below (using setInterval method), then it fails... Code: <script language="javascript" type="text/javascript"> function invoke() { var i=0; return i.x.y; } try { setInterval(alert('invoke())',1000); } catch(ex){ alert(ex); } //The Exception will NOT be caught. </script> any idea? thx in advance Similar TutorialsWhat happens in Javascript when you do not catch a thrown exception? Does the script get terminated prematurely? Double post I'm sorry. Please look at my other one.
Hey folks. I am needing some help with an error I'm getting from a project I'm working on. First off let me preface this all with the fact that I'm a total javascript noob. I'm really trying to understand what I'm doing wrong. So any help or advice is MORE than welcome. Here's what is happening. I found this code that will duplicate a row in a table and modifiy the name of a input in the row. Well for my purposes I have two different tables I need to work with. (each one idividually) So I changed the code a bit to make it accecpt a variable to use for the table name. (before it was static) and now I'm getting a error. Code: Error: uncaught exception: [Exception... "Component returned failure code: 0x80004003 (NS_ERROR_INVALID_POINTER)" nsresult: "0x80004003 (NS_ERROR_INVALID_POINTER)" location: "JS frame :: http://www.tourandtravelnow.com/admin/scripts/faxPageScript.js :: addRow :: line 14" data: no] This is the old code that would work (only for one of the tables) Code: var clone; function cloneRow(){ var rows=document.getElementById('mytab').getElementsByTagName('tr'); var index=rows.length; clone=rows[index-1].cloneNode(true); var inputs=clone.getElementsByTagName('input'), inp, i=0 ; while(inp=inputs[i++]){ inp.name=inp.name.replace(/\d/g,'')+(index+1); } } function addRow(){ var tbo=document.getElementById('mytab').getElementsByTagName('tbody')[0]; tbo.appendChild(clone); cloneRow(); } onload=cloneRow; and here is my code that doesn't work. Code: var clone; function cloneRow(mytab){ var rows=document.getElementById(mytab).getElementsByTagName('tr'); var index=rows.length; clone=rows[index-1].cloneNode(true); var inputs=clone.getElementsByTagName('input'), inp, i=0 ; while(inp=inputs[i++]){ inp.name=inp.name.replace(/\d/g,'')+(index+1); } } function addRow(mytab){ alert(mytab); var tbo=document.getElementById(mytab).getElementsByTagName('tbody')[0]; tbo.appendChild(clone); cloneRow(mytab); } onload=cloneRow(mytab); So like I said any help would AWESOME! have a great day. Kevin. Ok I have a script that uses some global arrays and a function that looks like this: function functName(p) The other params are optional so they are accessed using: functName.arguments[1] etc. My problem is an error that I can't seem to catch even though it's an easy one. array = (functName.arguments[1] != undefined && evel('window.' +functName.arguments[1]) != undefined) ? do this: or this; The second param is an arrayName. It can be sent to the function as a string or a reference ( string: 'arrayName' , ref: arrayName) both operate correctly unless the array doesn't exist. Entered as a string, if the array doesn't exist it defaults to another array as required. However, if posted as a reference and it doesn't exist it throws an error: 'arrayName' is undefined Should I just use a 'try catch' method or it just something simple I missed? Hi I'm an AS3 dev learning Javascript. I'm currently writing a simple script that loads an image as seen below. I deliberately misspell the file name to test the fail. Code: var fileName = "anImageThatDoesntExist.jpg"; var image = new Image(); image.onload = imageLoaded; try { image.src = "images/" + fileName; } catch( error ) { console.log('load error', error.message ); } finally { console.log('unable to catch error!') } function imageLoaded( event ) { console.log('image loaded'); } When I run this script I was expecting the 'catch' to pick up the error and tell me that the file doesn't exist. The 'catch' statement is ignored and 'finally' is executed. I would be very grateful if someone could let me know if I'm writing the try/catch incorrectly or whether it doesn't work in this way when loading an image. Many thanks in advance.... Hi, I've been working on a clock script that will appear on a frame of my site. Originally, I had used the following to refresh the page every second to the script shows the updated time and seconds. Code: <meta HTTP-EQUIV="Refresh" url="WEBSITE HERE" CONTENT="1"> This worked but unfortunately, there was the refresh "tick" sound every second, which became too annoying! I found the "setInterval" method and tried to apply it to my code. For the purpose of this thread, I've created another script similar to mine, but about 1/20 as long, though the result is the same. I would like it to re-run every second using setInterval, but it only runs once and then disappears. Code: <script type="text/javascript"> <!-- updateClock(); setInterval ("updateClock()", 1000); function updateClock() { var t = new Date(); var seconds = t.getSeconds(); document.write(seconds); } // --> </script> Any help would be appreciated!! Thanks. Hi Guys, I'm new to javascript and I'm trying to have a delay. I seem to be having trouble with the setInterval(). Will someone please be able to tell me what have I have done wrong? Code: function viewData() { var num = 10; setLoop(num); } function setLoop(i) { setInterval(loopOpacity(i), 300); } function loopOpacity(i) { i--; var iNum = "0." + i; document.getElementById("fade").style.opacity = iNum; if(i == 4) { document.getElementById("viewData").className = "view"; clearInterval(int); } else setLoop(i); } function closeData() { document.getElementById("fade").style.opacity = 1;; document.getElementById("viewData").className = "close"; } Thanks for your help, tecmeister. Hi all, I have a question about following code. It is tested as working well but the problem is that I need to catch values of array registos from javascript function getData(dataSource, sql_str) in PHP and not only update values of each form element. Can you help me, plz? Code: <script language = "javascript"> function getData(dataSource, sql_str){ if (window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest(); } else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ var registos = eval('('+xmlhttp.responseText+')'); document.getElementById("id_1").value=registos["cliente"]; document.getElementById("id_2").value=registos["designacao"]; } } xmlhttp.open("GET", dataSource+"&sql_str="+sql_str,true); xmlhttp.send(); } </script> <?php $sql_str="SELECT cliente, designacao WHERE cliente = '$cliente'"; $record=$db->sql_query($sql_str); list($registos[cliente], $registos[designacao]) = $db->sql_fetchrow($record); echo "<form id=\"form\">"; echo "<input type=\"text\" id=\"id_1\" name=\"registos[cliente]\" value=\"".$registos[cliente])."\">"; echo "<br>"; echo "<input type=\"text\" id=\"id_2\" name=\"registos[designacao]\" value=\"".$registos[designacao]."\">"; echo "<br>"; echo "<input type=\"button\" value=\"CONFIRMAR\" onclick=\"getData('mysql_query.php', '".base64_encode(serialize($sql_str))."')\">"; echo "</form>"; I've got a function that returns the value of a radio button group. However the application allows to "hide" some groups on others responses and that effectively make the radio groups not exist. This causes issues with calculations using the total value of the groups combined. I need a way to return a value of '0.00' IF the function does not find the group/returns an error.This is what I currently got to but doesnt work. The function does not work at all. Code: function funcRadioCalc(RadioName) { var chkList1= document.getElementById (RadioName); var arrayOfCheckBoxes= chkList1.getElementsByTagName("input"); var bob; try { for( var i=0;i<arrayOfCheckBoxes.length;i++){ if (arrayOfCheckBoxes[i].checked) { bob= arrayOfCheckBoxes[i].value; if (bob!=undefined||bob!=""){ throw "yep"; }else{ throw "nope"; } } } catch (er){ if(er=="nope") { return "0.00"; } if(er=="yep") { return bob; } } } In my mouseClick function I have a setInterval which call cursor function. Unfortunately it's not working. Below is my code: Code: var canvas; var ctx; var cursor_width = 1; var cursor_height = 16; var wait_time = 500; var repeat_time = 1000; var height = 22; var textbox = new Array(); var repeat; function Class(__proto__) { var Class = __proto__.hasOwnProperty("constructor") ? __proto__.constructor : (__proto__.constructor = function () {}); Class.prototype = __proto__; return Class; } Class.prototype = Function.prototype; function init(CanvasName) { canvas = document.getElementById(CanvasName); ctx = canvas.getContext("2d"); } //============================================= Textfield ============================================= textfield = new Class({ constructor: function (x, y, w) { this.x = x; this.y = y; this.w = w; this.text = new Array(); var coordinates = new Array(); coordinates.x = x; coordinates.y = y; coordinates.w = w; textbox.push(coordinates); }, display: function () { ctx.beginPath(); ctx.rect(this.x, this.y, this.w, height); ctx.closePath(); ctx.stroke(); canvas.addEventListener("mousedown", this.mouseClick, false); }, cursor : function () { this.cursor_posX = this.x + 3; this.cursor_posY = this.y + 3; ctx.beginPath(); ctx.strokeStyle = "black"; ctx.rect(this.cursor_posX, this.cursor_posY, cursor_width, cursor_height); ctx.closePath(); ctx.stroke(); setTimeout(this.animateCursor, wait_time); }, animateCursor :function () { ctx.strokeStyle = "white"; ctx.stroke(); }, mouseClick: function (evt) { var mouse_posX = evt.clientX - canvas.offsetLeft; var mouse_posY = evt.clientY - canvas.offsetTop; var self = this; // if mouse coordination is within a texfield display cursor for (child in textbox){ if((mouse_posX > textbox[child].x && mouse_posX < (textbox[child].x + textbox[child].w)) && (mouse_posY > textbox[child].y && mouse_posY < (textbox[child].y + height))) { repeat = setInterval(this.cursor, repeat_time); canvas.addEventListener("keypress", this.displayText, false); break; } else { clearInterval(repeat); canvas.removeEventListener("keypress", this.displayText, false); } } } }); I tried the following code as well but I received a message telling me it's not a function Code: repeat = setInterval("this.cursor()", repeat_time); Can anyone help me please Hello. I'm trying to get a script (and an html page, I guess) to run constantly, and I'm pretty sure I should be using setInterval() to do this. But I'm not familiar enough with Javascript to know what I'm doing wrong, or what I need to fix. This is the code... Code: <html> <head> <script type="text/javascript" src="wz_jsgraphics.js"></script> <script type="text/javascript"> <!-- function initialize_field() { var jg = new jsGraphics(); var pixel_spacer = 10; var field_length = 1000; var field_width = 600; jg.drawRect(pixel_spacer,pixel_spacer,field_length,field_width); //... return jg } function main() { our_field = initialize_field(); dateobj = new Date(); current_time = dateobj.getMilliseconds(); our_field.drawString("Hello world!",current_time,500); our_field.paint(); } --> </script> </head> <body onload="main(); setInterval('main()', 250 )"> </body> </html> If I understand setInterval() correctly, this should cause the page to run the main() function every 250 seconds. And within main(), the "Hello world!" string is being drawn at some point between 0 and 1000 pixels, depending upon the number of milliseconds, so it should essentially be scrolling across the screen. But I can only get it to "scroll" if I hammer F5 to repeatedly load the page. How can I get the main() function to run repeatedly? I tried calling main() from main(), but that did not work well... Thanks for any suggestions you have! Can anyone tell me how the following code actually works please? I've been trying to work out exactly why I need it all, but can't understand it at all! Code: var speed = 50 var myInterval var pause function start(){ window.clearInterval(pause) myInterval = setInterval("auto()",speed) } pause = setInterval("start()",3000) The body onLoad is set to run start(). If anyone can explain why this code is needed I would be very greatful. i have found a very simple ajaxexample on the internet, when this works i can adept it to my site, but it doesn't work :-( anybody sees why? Code: <div align="center" id="timeval">--:--:--</div> <button id="stop">Stop</button> <script src="jquery.js"></script> <script> $(document).ready(function() { //ajaxTime.php is called every second to get time from server var refreshId = setInterval(function() { $('#timeval').load('ajaxTime.php?randval='+ Math.random()); }, 1000); //stop the clock when this button is clicked $("#stop").click(function() { clearInterval(refreshId); }); }); </script> and the phpscript: ajaxtime.php <?php echo date("g:i:s A"); ?> Hey guys, Im playing around with JS trying to learn more and i have come across this bit of code Code: <script type="text/javascript"> function print () { document.write("Words "); } setInterval("print()", 1000); </script> Just having problems getting it to display correctly in all browsers its displaying the first Words fine in all but will only continue to reprint "Words" in chrome. Thanks any help tips ideas would be great. I have this: function doThese(id){ clearInterval(interval); doThis(id); var interval = function(){ setInterval("doThis('"+id+"')", 2000); } interval(); doThisToo(id); alsoDoThis(id); } Everything works fine together. However when I run the doThese() function a second time(with different id), the interval keeps using the id of the first run. Thought clearinterval would fix that.. it doesn't. Any suggestions? Thx in advance. How would you use setInterval so that theres a delay each time javascript runs through a certain loop?
Hello, I'm having trouble with some scripts conflicting and interrupting my animation. I have a small website build around Joomla and I do my own modules and components.. I've made a simple browser game that uses Javascript's setInterval to highlight some elements. A few days ago I decided to add some advertising banners to cover the server costs but those banners are using Javascript and are interrupting my "game"... Is there a way to stop that from happening ? The script flow goes like this... Step 1. An XMLHttpRequest is being made and the server returns X numbers of elements out of Y total elements that need to get highlighted. Step 2. The elements default state is "blank" then a loop goes through the Y elements and sets a className of "highlight" on the elements that need to get highlighted. Step 3. The setInterval is being called and executes the code that highlights the X elements on every interval. Code: mytimer = setInterval ( animation, 500 ); The animation variable holds a function that changes the elements with class "highlight" to "highlighted". Some pseudo-code: Code: // After all the AJAX requests and more doodle codes... while(i < num_arr.length) { // num_arr holds the X numbers to get marked as highlight document.getElementsByTagName('td').item(X).setAttribute('name', 'highlight'); i++; } mytimer = setInterval ( animation, 500 ); var animation = function() { document.getElementsByTagName('td').item(X).className = 'highlighted'; // There is an "if" check to kill the setInterval if no more Xs are found clearInterval(mytimer); } * The above code is just a short example of the actual script * Any help would be much appreciated.. Thank you. I would like to create a link from one page to another. Easy - I know. But I would like that link to to take me to a certain part of the other page, specifically towards the bottom of the page. Is that possible to do? And if so, what are the different ways I can specify where in the page to go? (i.e. what are the parameters that I can play with) Thanks! I am opening a blank window and writing a javascript on the new window to submit a form. when I execute a line "newWindow.document.write(newwdtxt2);\n\"(3rd line from last) I get an exception and last two lines do not execute. I see this problem only in IE 6, Code works fine with IE 7.Below mention is my code function openWindow(url,name,options) { var aToken = ""; aToken ="2121225434349231132674638921:something"; if(aToken=="") { aToken=document.formEMS.AUTHTOKEN.value; } var newWindow = window.open("", name); if (!newWindow) return false; var newwdtxt = ""; newwdtxt += "<html><head></head>\n"; newwdtxt += "<body>\n"; newwdtxt += "<form name=\"eventForm\" method=\"post\" action="+url+ ">\n"; newwdtxt += "<input type=\"hidden\" name=\"AUTHTOKEN\""; newwdtxt += "value= '";newwdtxt += aToken+"'/>\n"; newwdtxt += "</form>\n"; newwdtxt += "<scr"; var newwdtxt1 = ""; newwdtxt1 += "ipt type=\"text/javascript\" language=\"javascript\">\n"; newwdtxt1 += "window.onLoad=document.eventForm.submit();\n"; newwdtxt1 += "</scr"; var newwdtxt2 = ""; newwdtxt2 += "ipt>\n"; newwdtxt2 += "</body></html>\n"; newWindow.document.write(newwdtxt); alert(newwdtxt); newWindow.document.write(newwdtxt1); alert(newwdtxt1); alert(newwdtxt2); newWindow.document.write(newwdtxt2); alert('wrote newwdtxt2'); return newWindow; } Please help me to figure out what is the problem? Hi all, I'm new to Javascript, and having an issue with getInterval. For my programming languages class we have to create a simulation of waves breaking on a shore from above. I've decided to use a canvas object and Javascript for this animation, but am getting stuck on refreshing the frames. Here is the code I have so far: Code: var shoreline = new Array(); var waves = new Array(); var canWidth = 600; var canHeight = 400; var waveNum = 0; var count = 0; function wave() { setupShore(); var canvas = document.getElementById("canvas"); canvas.setAttribute("width",canWidth); canvas.setAttribute("height",canHeight); var ctx = canvas.getContext("2d"); createWave(); setInterval(update(ctx), 1000); } function update(ctx) { if(waves.length != 0) { drawWater(ctx); drawShore(ctx); drawWaves(ctx); updateWaves(); } } function drawElement(ctx, x, y, width, height, fillcolor) { ctx.fillStyle = fillcolor; ctx.fillRect(x, y, width, height); } function setupShore() { for(var i = 0; i <= canWidth/5; i++) { shoreline[i] = Math.round(canHeight/5); // + Math.floor(Math.random()*101); } } function createWave() { /* Wave array setup: [ [waveID1, [node1, node2, ..., nodeN]], [waveID2, [node1, node2, ..., nodeN] ] */ waves.push([waveNum, []]); for(var c = 0; c <= canWidth/5; c++){ waves[waves.length-1][1].push(canHeight); } waveNum = waveNum + 1; } function destroyWave() { waves.shift(); } function drawWater(ctx) { drawElement(ctx, 0, 0, canWidth, canHeight, "#336699"); } function drawShore(ctx) { for(var s = 0; s <= shoreline.length; s++) { drawElement(ctx, s*5, 0, 5, shoreline[s], "#FFCC00"); } } function updateWaves() { for(var u = 0; u < waves.length; u++) { var limit = waves[u][1].length; for(var v = 0; v < limit; v++){ var temp = waves[u][1][v]-5; waves[u][1][v] = temp; if(waves[u][1][v] <= shoreline[v]){ destroyWave(); } } } } function drawWaves(ctx) { for(var w = 0; w < waves.length; w++) { for(var n = 0; n <= waves[w][1].length; n++){ y = waves[w][1][n]; drawElement(ctx, n*5, y, 5, 5, "Purple"); } } } As you can see, the idea is that each 5-pixel wide node of the shore and wave are stored in arrays so that the position of each node can differ. The wave() function initializes all the required data, and then calls setInterval on update(). The function update() draws the water, shore, and wave, and then updates the wave position node-by-node. Ideally, setInterval would cause this to happen repeatedly, so that the wave would appear to move closer to the shore every 1000ms. However, this is not the case. It appears as though setInterval is working for one pass of update(), but fails after the first pass. You can tell that this is happening because the wave appears at its starting position, but does not continue to move. Any idea why this is happening? I read somewhere that setInterval can be broken by one-time functions, but I'm not sure. If you'd like to see what it's currently doing in a browser, I've hosted it here. Once I've got this animating properly I can continue my project, but I've hit a roadblock. Thanks in advance for your help, I'm really stuck. Marcus |