JavaScript - Setinterval Conflicts
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. Similar TutorialsFor a widget I made, I have a dropdown select menu. It is constrained to a very small width and IE does not auto expand on click. I wrote a simple javascript to handle this but I run into two problems. The onmouseout function is fired when I click into a child node, and the onmousedown of the <option> tags doesn't work in IE. The code works fine in all other browsers. var wid; var campaign_i = 0; function campaignWidget_capture(myID){ wid=document.getElementById(myID).style.width; campaign_i++; } function campaignWidget_SubDes(myID,state){ if(state==0){ if(campaign_i==0) campaignWidget_capture(myID); document.getElementById(myID).style.width="auto"; }else document.getElementById(myID).style.width=wid; } onmouseout="campaignWidget_SubDes(id,1)" This is in the select tag. onmousedown="campaignWidget_SubDes(id,0)" This is in the select tag onmousedown="campaignWidget_SubDes('campaignWidget_Sub_Designation',1)" This is in the option tag. I have been given the task of merging all of the javascript of 3 different websites into one file. I think that some of the JS is conflicting, but I don't know. I am not that experienced with JavaScript. Some of the JS is using jQuery. I have multiple anonymous jQuery functions: Code: (function ($) { // Javascript code })(jQuery) Notepad++ tells me there are 7 instances of: Code: (function (a) I am guessing there is no doubt that would cause conflict? What are some common things that cause conflicts in JavaScript? Hi Guys, i'm a complete amateur when it comes to js so would appreciate your help! I'm trying to implement two different JQuerys at the same time (vertical scrolling & shadowbox). When I try one of them on its own, it works fine, however when I add the second coding, it all stops working! I''ve read a few forums suggesting solutions, but frankly I don't really understand it!! Here is the HTML coding: 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>Untitled Document</title> <link href="css/stylesheet.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" type="text/css" href="css/shadowbox.css" /> <script type="text/javascript"> function MM_swapImgRestore() { //v3.0 var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc; } function MM_preloadImages() { //v3.0 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array(); var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++) if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}} } function MM_findObj(n, d) { //v4.01 var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) { d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);} if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n]; for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); if(!x && d.getElementById) x=d.getElementById(n); return x; } function MM_swapImage() { //v3.0 var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3) if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];} } </script> </head> <body onload="MM_preloadImages('images/btns/header_hyperlinks/contactus(2).png','images/btns/header_hyperlinks/about(2).png','images/btns/header_hyperlinks/hire(2).png','images/btns/header_hyperlinks/specialevents(2).png','images/btns/header_hyperlinks/latestnews(2).png','images/btns/header_hyperlinks/whatson(2).png','images/btns/header_hyperlinks/home(2).png','images/btns/header_hyperlinks/tickets(2).png','images/whatson_imgs/tickets_btn(2).png','images/whatson_imgs/calender_btn(2).png')"> <div id="header"> <div id="header_btns"> <div class="b1"><ul class="nav"><a href="#container" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('home_btn','','images/btns/header_hyperlinks/home(2).png',1)"><img src="images/btns/header_hyperlinks/home(1).png" name="home_btn" width="70" height="19" border="0" id="home_btn" /></ul></a></div> <div class="b1"><ul class="nav"><a href="#whatson_container" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('whatson_btn','','images/btns/header_hyperlinks/whatson(2).png',1)"><img src="images/btns/header_hyperlinks/whatson(1).png" name="whatson_btn" width="113" height="19" border="0" id="whatson_btn" /></ul></a></div> <div class="b1"><ul class="nav"><a href="#latestnews_container" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('latest_btns','','images/btns/header_hyperlinks/latestnews(2).png',1)"><img src="images/btns/header_hyperlinks/latestnews(1).png" name="latest_btns" width="132" height="19" border="0" id="latest_btns" /></ul></a></div> <div class="b1"><a href="#" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('special_btn','','images/btns/header_hyperlinks/specialevents(2).png',1)"><img src="images/btns/header_hyperlinks/specialevents(1).png" name="special_btn" width="156" height="23" border="0" id="special_btn" /></a></div> <div class="b1"><a href="#" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('tickets_btn','','images/btns/header_hyperlinks/tickets(2).png',1)"><img src="images/btns/header_hyperlinks/tickets(1).png" name="tickets_btn" width="81" height="19" border="0" id="tickets_btn" /></a></div> <div class="b1"><a href="#" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('hire_btn','','images/btns/header_hyperlinks/hire(2).png',1)"><img src="images/btns/header_hyperlinks/hire(1).png" name="hire_btn" width="50" height="19" border="0" id="hire_btn" /></a></div> <div class="b1"><a href="#" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('about_btn','','images/btns/header_hyperlinks/about(2).png',1)"><img src="images/btns/header_hyperlinks/about(1).png" name="about_btn" width="203" height="19" border="0" id="about_btn" /></a></div> <div class="b2"><a href="#" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('contact_us','','images/btns/header_hyperlinks/contactus(2).png',1)"><img src="images/btns/header_hyperlinks/contactus(1).png" name="contact_us" width="120" height="19" border="0" id="contact_us" /></a></div> </div> </div> <div id="container"> <div id="logo"> <img src="images/logo.png" /> </div> </div> <div class="wrapper"> <div class="seperator"> <img src="images/blank.png" height="100%" /> </div> <br /><a href="#" class="hyperlink">Read more..</a> </h3> </div> <div class="news_sections"> </div> <div class="news_sections2"> </div> </div> </div> </body> <!-- ================== JAVASCRIPT FOR THE SCROLLING ================== --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript" src="js/jquery.easing.1.3.js"></script> <script type="text/javascript"> $(function() { $('ul.nav a').bind('click',function(event){ var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500,'easeInOutExpo'); /* if you don't want to use the easing effects: $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1000); */ event.preventDefault(); }); }); </script> <!-- ================== END OF JAVASCRIPT FOR THE SCROLLING ================== --> <!-- ================== JAVASCRIPT FOR THE SHADOWBOX ================== --> <script type="text/javascript" src="js/jquery.js" /></script> <script type="text/javascript" src="js/shadowbox.js"></script> <script type="text/javascript"> Shadowbox.init(); function MM_swapImgRestore() { //v3.0 var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc; } function MM_preloadImages() { //v3.0 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array(); var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++) if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}} } function MM_findObj(n, d) { //v4.01 var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) { d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);} if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n]; for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); if(!x && d.getElementById) x=d.getElementById(n); return x; } function MM_swapImage() { //v3.0 var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3) if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];} } </script> <!-- ================== END OF JAVASCRIPT FOR THE SHADOWBOX ================== --> </html> Your help will be much appreciated! Ok my lab6 at http://opentech.durhamcollege.ca/~in...rittains/labs/ is conflicting with my interface as it is php... is there a better way for me to do this that will allow it to not conflict? PHP Code: <?php $title = "Lab6"; include "head.php"; ?> <style type="text/css"> table, td, th { border: 1px solid red; } </style> <?php function convert($i) { $CtoF= 9.0/5.0*$i + 32; return $CtoF; } ?> <td> <?php $error = ""; $result = ""; if($_SERVER["REQUEST_METHOD"] == "GET") { $start = ""; $stop = ""; $increment = ""; } else if($_SERVER["REQUEST_METHOD"] == "POST") { $start = trim($_POST["startTemp"]); $stop = trim($_POST["stopTemp"]); $increment = trim($_POST["incrementTemp"]); if(!isset($start) || $start == "") { $error .= "<br/>Please enter number to declare a starting value."; } else if(!is_numeric($start)) { $error .= "<br/>The value entered <b>MUST</b> be a number, you entered: " . $start; $start = ""; } if(!isset($stop) || $stop == "") { $error .= "<br/>Please enter number to declare a ending value."; } else if(!is_numeric($stop)){ $error .= "<br/>The value entered <b>MUST</b> be a number, you entered: " . $stop; $stop = ""; } if(!isset($increment) || $increment == "") { $error .= "<br/>Please enter number to declare a increment value."; } else if(!is_numeric($increment)){ $error .= "<br/>The value entered <u>MUST</u> be a number, you entered: " . $increment; $increment = ""; } if($error == "") { $result .= "<table class='phpTable'>"; $result .= "<tr><th>Celsius</th>"; $result .= "<th>Fahrenheit</th></tr>"; for ($i = $start; $i <= $stop; $i += $increment) { $result .= "<tr><td>" . $i; $result .= "°</td><td>"; $result .= convert($i); $result .= "°</td></tr>"; } $result .= "</table>"; } else { $error .= "<br/>Please Try Again"; } } ?> <script type="text/javascript"> /*var error = "<?php echo $error; ?>"; document.getElementById('error').innerHTML = error; var result = "<?php echo $result; ?>"; document.getElementById('result').innerHTML = result;*/ </script> <h2 id="error"><?php echo $error; ?></h2> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" > Starting Temperatu <input type="text" name="startTemp" value="<?php echo $start; ?>" size="5"/> <br/> Stop Temperatu <input type="text" name="stopTemp" value="<?php echo $stop; ?>" size="5"/> <br/> Temperature Increment: <input type="text" name="incrementTemp" value="<?php echo $increment; ?>" size="5"/> <br/> <input type="submit" name="submit" value="Submit"/> </form> <h2 id="result"><?php echo $result; ?></h2> <?php include "foot.php"; ?> The assignment was supposed to be done in PHP. But I want to know if there is a better way either way. Like can I use AJAX instead of PHP to do that? or change the way the PHP works... something anything... Hello. I just added this javascript/css dropdown menu to my site (download came from here). Everything seemed to be going fine until I started to test it on other pages. It seems to be running into some sort of conflict on certain pages, but I have no idea why or how. All I can tell is that the page loads differently (it shows basically an un-styled site, then it loads) and that's when the conflict occurs. In short, the menu shows up about 50px below where it should, rendering it impossible to use. I don't care how it looks in IE. The only browser that is showing it correctly is Opera. Any help would be greatly appreciated. I have no idea. :/ http://www.surrealtwilight.com You'll have to login with "Reviewer" password "testingme" to see the layout I've been working on. Menu works fine on the index page and some other pages, but not for the website pages like st_rules.php and stuff like that. :/ Any help will be greatly appreciated. I love how it looks, and I'm super bummed it's doing this. On one of my pages, I have a dropdown menu as well as a image rotator. The problem is that when I have the menu on a page by itself, it loads like this: Not only does it have arrows, it also loads with a fade in/out. This is what I want. However, when both menu and image rotator scripts are in the head, this is the result: it doesnt have the arrows and doesnt fade in/out. Could someone point out where the two scripts come into conflict and possibly a resolution? Here is the code in the head: Code: <!--main stylesheet--> <link rel="stylesheet" type="text/css" href="css/main.css"> <!--menu stylesheets--> <link rel="stylesheet" type="text/css" href="css/superfish.css" media="screen"> <script type="text/javascript" src="js/jquery-1.2.6.min.js"></script> <script type="text/javascript" src="js/hoverIntent.js"></script> <script type="text/javascript" src="js/superfish.js"></script> <script type="text/javascript"> // initialise plugins $(document).ready(function(){ $("ul.sf-menu").superfish(); }); </script> <!--Orbit stylesheets--> <!-- Use the ID of your slider here to avoid the flash of unstyled content --> <style type="text/css"> #featured { width: 940px; height: 450px; background: #009cff url('orbit/loading.gif') no-repeat center center; overflow: hidden; } </style> <link rel="stylesheet" href="orbit.css"> <!--[if IE]> <style type="text/css"> .timer { display: none !important; } div.caption { background:transparent; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000,endColorstr=#99000000); zoom: 1; } </style> <![endif]--> <!-- Attach necessary scripts --> <script type="text/javascript" src="js/jquery-1.4.1.min.js"></script> <script type="text/javascript" src="js/jquery.orbit.min.js"></script> <!-- Run the plugin --> <script type="text/javascript"> $(window).load(function() { $('#featured').orbit({ 'bullets': true, 'timer' : true, 'animation' : 'horizontal-slide' }); }); </script> This is probably stupid on my part so, I apologize in advance. I created a simple script/function that generates a popup window when you click on a link. The function writes the html code for a media player (the URL for which is passed to the function) depending on what link is clicked, and then creates a text link "Close" below the player. I've put the code below... BUT! Here's what's happening. I tested it on both Firefox and Google Chrome. (I could swear it was working on both once upon a time...but now just isn't...) In Chrome, the player is visible but the close link is not. In Firefox, the player is not visible(but you can find where it's at and pause/resume and etc.) The close link is visible. The audio file plays on both browsers. The window is supposed to have a black background, which is does in Firefox but for some reason it's blue in Chrome? (Minor issue..I know...) Quote: function pop(url) { var generator=window.open('','name','height=200,width=400,status=1'); generator.document.write('<html><head><title>Popup</title>'); generator.document.write('</head><body style="color:white;" bgcolor="#000">'); generator.document.write('<object width="300" height="200"><param name="src" value="' + url + '"><param name="autoplay" value="false"><param name="controller" value="true"><param name="bgcolor" value="#CCCCCC"><embed src="' + url + '" autostart="true" loop="false" width="300" height="200" controller="true" bgcolor="#CCCCCC"></embed></object>'); generator.document.write('<p><a style="color:white;" href="javascript:self.close()">Close</a> the popup.</p>'); generator.document.write('</body></html>'); generator.document.close(); } I can give you the URL for the thing so you can see it in action... http://thetabbfamily.com/cdpages/lifeisgood.php Scroll down 'Purchase Individuals' and click on one of the songs... 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, 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. I have a few hundred popups that I am trying to change to a "lightbox" style solution: Code: <!DOCTYPE html> <html> <head> <title>Test 1</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script> <script src="../../js/jquery.colorbox-min.js"></script> <link rel="stylesheet" href="../../css/colorbox5.css" media="screen"> <script src="../../js/ssm.js" type="text/javascript"></script> <script src="../../js/ssmitems3a.js" type="text/javascript"></script> <link rel="stylesheet" href="../../css/ssmitems.css" type="text/css"> <script> $(document).ready(function(){ $("a[rel='tip']").colorbox(); }); </script> </head> </script> <body> <a rel="tip" href="tip1(AC)2.html"><img border="0" src="../../img/tipani1.gif" width="50" height="74"></a> </body> </html> The new colorbox popup solution works well, but in some browsers - notably IE - it conflicts with the SIDE MENU routine I use. I think the menu is old code, but it works. However, to get the new "lightbox-style" popup to work in IE, I have to include <!DOCTYPE html>. In the other browsers, omitting the declaration apparently solves the conflict problem (but I feel it ought to be there). I really don't know what to do. Tinker with the side menu code? Here is a demo with the <!DOCTYPE html> declaration: http://www.aapress.com.au/ieltsonlin...conflict1.html ...and without it: http://www.aapress.com.au/ieltsonlin...conflict2.html I have tried with a full declaration but it makes no difference at all. And further reading online suggests <!DOCTYPE html> is OK. Does anyone spot a reason for the conflict? 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 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. 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. 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! 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 How would you use setInterval so that theres a delay each time javascript runs through a certain loop?
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, I'm trying to use the setInterval method for a function, but it's not working. Here's the code. Code: function interval_demo() { function int_sum() { alert("I will add two numbers for you, and then add another extra number!"); var n1 = prompt("What's your first number?", ""); var n2 = prompt("What's your second number?", ""); var sum = n1 + n2; return sum; } window.setInterval('int_sum()', 1000); } window.onload = interval_demo; The function works fine if I use window.setInterval('int_sum', 1000). What's the problem with setInterval('int_sum()', 1000)? Correct me if I'm wrong, but isn't that also a valid way to call functions in the setInterval method? Thanks! 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 I found a little chat script online and I wanted to check it out. When I integrated it into a page I created, for some reason this will not work correctly <body onload="setInterval('chat.update()', 1000)"> I tested it with two different browswers open Lets say on two different browser windows you have user1 and user2 if user1 types 'Hello' it will not show up on user2 window but if user2 types 'Hi' then on user2 window it will say user1 says Hello user2 says Hi so basically for user1 to see what user2 has wrote, user1 has to type something first and send it to see what user2 said. hope you understand, if you would like I could post up the code. |