JavaScript - Calling Settimeout In A Loop
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> <style type="text/css"> #status { background-color:#FF0; width: 300px; height: 150px; overflow:scroll; margin-top: 25px; } #money { position:absolute; left: 325px; top: 416px; } </style> <script type="text/javascript"> function Machine() { this.getCash = function() { var i = 0; var rand = 0; while (i < 2) { t = setTimeout("rand = Math.ceil(Math.random() * 4 )", 1000); alert(rand); i++; } clearTimeout(t); } } var soda = new Machine(); soda.getCash(); </script> </head> <body> <div style="margin-bottom:25px"> Soda Machine. <p>_________________</p> 1. Earn Money <br /> 2. Buy Soda </div> <table> <thead> <th>Soda</th> <th>Price</th> <th>Buy</th> </thead> <tbody> <tr> <td> Basic Fizz </td> <td> $5 </td> <td> <input type="button" id="b_fizz" value="Buy Basic Fizz" /> </td> </tr> <tr> <td> Advanced Fizz </td> <td> $11 </td> <td> <input type="button" id="a_fizz" value="Buy Advanced Fizz" /> </td> </tr> <tr> <td> The Good Stuff </td> <td> $17 </td> <td> <input type="button" id="cc_fizz" value="Buy Coca Cola" /> </td> </tr> </tbody> </table> <div id="status"> <p style="margin-top:0">Status Window: </p> </div> <input type="text" id="money" value="$0" disabled="disabled" /> <input type="button" id="earn" value="Earn Cash" /> </body> </html> Basically, what I'm trying to do is get a random number every second for 2 seconds automatically so that in the status window it says: "You earned $2" "You earned $3" ....etc. But my random number keeps showing up as 0. I know I'm probably overlooking something as far as closures...can someone please enlighten me? Check the javascript code tried this also..same result for everything I try: D: Code: function Machine() { this.rand = 0; this.r = function() { this.rand = Math.ceil(Math.random() * 4); } this.getCash = function() { var i = 0; while (i < 3) { t = setTimeout("this.r()", 1000); alert(this.rand); i++; } clearTimeout(t); } } var soda = new Machine(); soda.getCash(); Similar TutorialsHi, this must be simple but I don't get it work. I need to do the following delay within a loop: var position; for ( var i=1; i < 100; i++) { position++; setTimeout("", 1000); // delay for loop; } // end for loop; It does not work, because setTimeout needs always the function parameter within the "". There must be a way around this !? Thanks you for your help ! Claus Ok, I'm nearly pulling my hair out with this one. I have been looking at this code for two evenings now, and rewrote it 4 times already. It started out as jQuery code and now it's just concatenating strings together. What I'm trying to do: Build a menu/outline using unordered lists from a multidimensional array. What is happening: Inside the buildMenuHTML function, if I call buildMenuHTML, the for loop only happens once (i.e. only for 'i' having a value of '0'.) If I comment out the call to itself, it goes through the for loop all 3 times, but obviously the submenus are not created. Here is the test object: Code: test = [ { "name" : "Menu 1", "url" : "menu1.html", "submenu" : [ { "name" : "menu 1 subitem 1", "url" : "menu1subitem1.html" }, { "name" : "menu 1 subitem 2", "url" : "menu1subitem2.html" } ] }, { "name" : "Menu 2", "url" : "menu2.html", "submenu" : [ { "name" : "menu 2subitem 1", "url" : "menu2subitem1.html" }, { "name" : "menu 2subitem 1", "url" : "menu2subitem1.html" } ] }, { "name" : "Menu 3", "url" : "menu3.html", "submenu" : [ { "name" : "menu 3 subitem 1", "url" : "menu3subitem1.html" }, { "name" : "menu 3 subitem 1", "url" : "menu3subitem1.html" } ] } ]; Here is the recursive function: Code: function buildMenuHTML(menuData,level) { var ul; if (level == 1) { ul = "<ul id='menu'>"; } else { ul = "<ul class='level" + level + "'>"; } for (i = 0; i < menuData.length; i++) { menuItemData = menuData[i]; ul += "<li>"; ul += "<a href='" + menuItemData.url + "'>" + menuItemData.name + "</a>"; if (typeof menuItemData.submenu != 'undefined') { ul += buildMenuHTML(menuItemData.submenu,level + 1); } ul += "</li>"; } ul += "</ul>"; return ul; } Here is how the function is called initially: Code: buildMenuHTML(test,1); This is it's return value (with indentation added for readability): Code: <ul id='menu'> <li><a href='menu1.html'>Menu 1</a> <ul class='level2'> <li><a href='menu1subitem1.html'>menu 1 subitem 1</a></li> <li><a href='menu1subitem2.html'>menu 1 subitem 2</a></li> </ul> </li> </ul> 'Menu 2' and 'Menu 3' don't show up! I'm sure it's something small that I'm overlooking, but any help would be appreciated. I have a while-loop and I need it to make a little delay before each time it starts a new cycle. Code: var rollOn = true; while(rollOn) { //A bunch of statements. //The loop breaks in case of certain conditions so that "rollOn = false;". var t = setTimeout("continue", 1000); } //End while The problem is that setTimeout doesn't delay for a second before the "continue" statement. For example, when I write: Code: var t = setTimeout("alert("Delay")", 1000); then it displays the alert box after every cycle of the loop, but still no delay. There are no error messages or anything, I'm not really sure what's the problem, thus I don't know what to do about it. Any ideas? Hi Everyone, I am not able to figure out why the function "changeDiv(the_div,the_change)" is not called from the for loop in the function displayUsers(keeper)that I generated. The displayUsers is written to get rid of excess code in the function display(keeper). Can someone, please point out what the mistake is? Code: function changeDiv(the_div,the_change) { var the_style = getStyleObject(the_div); if (the_style != false) { the_style.display = the_change; } } function getStyleObject(objectId) { if (document.getElementById && document.getElementById(objectId)) { return document.getElementById(objectId).style; } else if (document.all && document.all(objectId)) { return document.all(objectId).style; } else { return false; } } //Shows input information for # of users selected function displayUsers(keeper) { var display=keeper; var i,user; for(i=1;i<= display;i++) { user="user"+i; changeDiv('user','block'); } } /*function display(keeper) { if (keeper == 1) { changeDiv('user1', 'block'); changeDiv('user2', 'none'); changeDiv('user3', 'none'); changeDiv('user4', 'none'); changeDiv('user5', 'none'); changeDiv('user6', 'none'); changeDiv('user7', 'none'); changeDiv('user8', 'none'); changeDiv('user9', 'none'); changeDiv('user10','none'); } else if (keeper == 2) ... ... ... else { changeDiv('user1', 'none'); changeDiv('user2', 'none'); changeDiv('user3', 'none'); changeDiv('user4', 'none'); changeDiv('user5', 'none'); changeDiv('user6', 'none'); changeDiv('user7', 'none'); changeDiv('user8', 'none'); changeDiv('user9', 'none'); changeDiv('user10','none'); } }// end function display(keeper)*/ I'm hoping someone can help correct a small problem with this script, which is intended to highlight particular text strings. Background: The script is being used at a MediaWiki site, and is adapted from a working script from Wikipedia (highlightmyname.js). The original script highlights the logged-in user's username (represented by wgUserName). I've made a copy of the script, which you can see in full here, and adapted it to work on a pre-defined array of names, adding: Code: var Admin; var ArrayAdmins = ['Adam', 'Axiomist', 'Matt', 'Steve']; for (Admin in ArrayAdmins) I also replaced each instance of wgUserName with ArrayAdmins[Admin] The problem: is that, instead of highlighting all instances of every element in ArrayAdmins, only the last element listed ('Steve') is being used. So my question is, what change(s) need to be made to apply function highlightmyname to every element in ArrayAdmins? Any help would be hugely appreciated! 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 ! 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... 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()"> 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 all, I am trying to do a simple "animation" of the background color of a button. I want it to do 10 different colors in the course of 1 second. I have a loop like this (pseudo code): Code: var e = "the button element"; var c = 10; while (c--) { setTimeout(function(){ e.style.backgroundColor=(random color); }, (c * 100)); } I expect that 10 instances of "setTimeout" would be created, each one timing out 0.1 seconds later than the previous one, giving me an "animation" of 10 different colors over the course of 1 second. Strangely, it doesn't work. All it does is WAIT one second, then set the background to the LAST color. What am I doing wrong? I can't see it. Thanks! -- Roger Edit: I also tried to do the loop forward instead... no difference. 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, i'm making a page with an image on it. when that image is clicked i want it to make one div visible, and also run the javascript function to make a second div visible after 2 seconds. Everything seems to work correctly except that the javascript runs on page load instead of waiting for when the image is clicked. any help much appreciated. thanks! Here's the javascript: <code <script type="text/javascript"> function showIt() { document.getElementById("show_1").style.visibility = "visible"; } setTimeout("showIt()", 2000); </script> </head> </code> Here's the html: <code> <div id="flyer1">content <div id="show_1" style="visibility:hidden">content </div> </div> <div id="image"> <a href="javascript:void(0)" onclick="MM_showHideLayers('flyer1', '','show')"; "showIt()">image</a> </div> </code> Im fairly new to javascript, i have mostly been into php i have this code i wrote in one of my projects and i assume theres an easier way Code: setTimeout("check20()", 0); setTimeout("check19()", 50); setTimeout("check18()", 100); setTimeout("check17()", 150); setTimeout("check16()", 200); setTimeout("check15()", 250); setTimeout("check14()", 300); setTimeout("check13()", 350); setTimeout("check12()", 400); setTimeout("check11()", 450); setTimeout("check10()", 500); setTimeout("check9()", 550); setTimeout("check8()", 600); setTimeout("check7()", 650); setTimeout("check6()", 700); setTimeout("check5()", 750); setTimeout("check4()", 800); setTimeout("check3()", 850); setTimeout("check2()", 900); setTimeout("check()", 950); basically every 50 javascript seconds a function is activated, so that means i have a **** ton of function too all doing the same thing just to different ids If you know of a better way let me know please I have a code snippet here. Everything in it works as expected. However the setTimeout does not seems to be working. It should be an infinite loops updating the contents of the table every 5 sec. However the table shows once when first called and the setTimeout never seems to kick in. Any help in getting that loop to work would be greatly appreciated. Code: statTick : function (){ var t = Tabs.Train; var m = '<TABLE class=pbTabPad>'; clearTimeout (t.statTimer); for (var c=0; c<Seed.s.cities.length; c++){ var last = serverTime(); var trains = []; m += '<TR><TD>City #'+ (c+1) +' '; for (var t=0; t<Seed.s.cities[c].jobs.length; t++){ if (Seed.s.cities[c].jobs[t].queue=='units' && Seed.s.cities[c].jobs[t].unit_type) trains.push (Seed.s.cities[c].jobs[t]); } if (trains.length == 0) m += 'idle</TD></TR>'; else { for (var j=0; j<trains.length; j++){ var left='', tot=''; if (j==0) left = 'Training '; else if (j==trains.length-1) tot = '   <B>('+ timestrShort(trains[j].run_at-serverTime()) +')</b>'; m += left + trains[j].quantity +' '+ trains[j].unit_type + ' '+ timestr(trains[j].run_at-last, true) + tot +'</TD></TR>'; last = trains[j].run_at; } } } document.getElementById('pbtrnTrnStat').innerHTML = m +'</table>'; t.statTimer = setTimeout (t.statTick, 5000); }, I want to delay image load for 3 seconds and here is the code but it doesnt work... HELP PLEASE <img id="img444" src="http://imakeinternet.com/squeeze/finish.png" style="display: none;"> <script> function showimage() { document.getElementById("img444").src="http://imakeinternet.com/squeeze/finish.png"; } setTimeout ("showimage();", 3000); </script> 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. I wrote the code below to animate a roll of dice. It does iterate 10 times, as the code intends, but for some reason it doesn't pause in between. Also, how can I get it to return the final dice value to the calling function? Code: DiceValue=RollDiceAnimated(1) function RollDiceAnimated(RollIteration) { var Die1;var Die2 var RollSpeed=100 Die1=0;while(Die1<1 || Die1>6){Die1=Math.floor(Math.random()*7)} Die2=0;while(Die2<1 || Die2>6){Die2=Math.floor(Math.random()*7)} document.getElementById("Dice1").src="Images_Dice/Dice" + Die1 + ".jpg" document.getElementById("Dice2").src="Images_Dice/Dice" + Die2 + ".jpg" if(RollIteration<10){ var tempval=setTimeout(RollDiceAnimated(RollIteration+1),RollIteration*RollSpeed) } else{return Die1+Die2} } So I have a very simple block of code: Code: function successfulReg() { alert(1); // $.colorbox({ html: '<p>Registration successful!</p>' }); } if ($('#regSuc').size()) setTimeout('successfulReg', 1000); If the regSuc item exists (1 second after the page loads), I want to bring up a lightbox. As I couldn't get this to work, I tried to get an alert to show up. This did not work either. I changed the setTimeout to Code: if ($('#regSuc').size()) setTimeout('alert(1), 1000); Which did work. And I tried successfulReg and succesfulReg(), neither of which worked. Am I missing some basic element to getting a timeout to work? 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 |