JavaScript - Help With Setting A Delay For A Loop (settimeout Isn't Helping)
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? Similar TutorialsI'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 Hi, 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 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(); i need to make a function that will send a string to my perl script then recieve the answer and set a div innerhtml to the answer.. i plan on sending the string from the div onload as i will have about 30 divs that need changing. Code: <body> <div name="example1" onload="javascript:retrieve('getstring1')">my retieved string1</div> <div name="example2" onload="javascript:retrieve('getstring2')">my retieved string2</div> </body> <head> <SCRIPT language="JavaScript"> function retieve('var') { } </SCRIPT> </head> im not quite sure where to go with this but i can easily make the perl script do if statements on the string and return the correct string to put into the div. the reason for this is that the string will be changed every couple weeks. there is probably a better way to do this but this would be more appropriate for me This is what I have: Code: <script type="text/javascript"> $(document).ready(function(){ $('#add').click(function() { alert ('test') }); $("form#exercise").submit(function() { // we want to store the values from the form input box, then send via ajax below var activity = $('#activity').attr('value'); $.ajax({ type: "POST", url: "newActiveProc.php", data: "activity="+ activity +"&func=search", success: function(msg){ $("span#results").html(msg); } }); return false; }); }); </script> Instead of alerting the user, I want to send their choice to the a table on the same page. Does anyone have any idea of how I might do this. I've posted three threads in the ajax forum with no response. Hello how can I add a time delay to a function, so that the called function will execute only after a certain length of time. For example if I want a div to go 'hidden', 3 seconds after hovering off of a second div? Here is the script code I'm wanting to add the delay to: Code: <script> function show(id) { document.getElementById(id).style.visibility = "visible"; } function hide(id) { document.getElementById(id).style.visibility = "hidden"; } </script> and Code: <div id="div1" onmouseover="show('div2'); fade_in('div2', 2);" onmouseout="fade_out('div2', 2); hide('div2');"> The reason I need this delay is so the fadeout function (which also executes after hovering off the second div completely finishes the fadeout before the hidden function executes. Hi all. The below script is from suckerfish. Can anyone help me include a 'one sec delay' to keep the menu open onmouseout. First menu often closes too fast before I get a chance to move onto submenu. I've tried everything with setTimeout BUT I just can't get it right. Nothing I do works. Can somebody PLEASE show me so I can kick myself. LT Code: <script type="text/javascript"><!--//--><![CDATA[//><!-- sfHover = function() { var sfEls = document.getElementById("nav").getElementsByTagName("LI"); for (var i=0; i<sfEls.length; i++) { sfEls[i].onmouseover=function() { this.className+=" sfhover"; } sfEls[i].onmouseout=function(){ this.className=this.className.replace(new RegExp(" sfhover\\b"), ""); } } } if (window.attachEvent) window.attachEvent("onload", sfHover); //--><!]]></script> Hi I am creating an animation based on Sam Dunn's tutorial 'Animate Curtains Opening with jQuery' ( http://buildinternet.com/2009/07/ani...g-with-jquery/ ). What i need to do is create a 2 second delay in the curtains opening in order to give enough time for an iframe, thats behind the curtains, to load it's content. Here is Sam's script : ----------------------------------------------------------------- <!-- Animate a Curtain Opening with jQuery index.html By Sam Dunn 2009 Build Internet! www.buildinternet.com --> <!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" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>Animate a Curtain Opening with jQuery | Build Internet</title> <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"></script> <script src="jquery.easing.1.3.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { $curtainopen = false; $(".rope").click(function(){ $(this).blur(); if ($curtainopen == false){ $(this).stop().animate({top: '0px' }, {queue:false, duration:350, easing:'easeOutBounce'}); $(".leftcurtain").stop().animate({width:'60px'}, 2000 ); $(".rightcurtain").stop().animate({width:'60px'},2000 ); $curtainopen = true; }else{ $(this).stop().animate({top: '-40px' }, {queue:false, duration:350, easing:'easeOutBounce'}); $(".leftcurtain").stop().animate({width:'50%'}, 2000 ); $(".rightcurtain").stop().animate({width:'51%'}, 2000 ); $curtainopen = false; } return false; }); }); </script> <style type="text/css"> *{ margin:0; padding:0; } body { text-align: center; background: #4f3722 url('images/darkcurtain.jpg') repeat-x; } img{ border: none; } .leftcurtain{ width: 50%; height: 495px; top: 0px; left: 0px; position: absolute; z-index: 2; } .rightcurtain{ width: 51%; height: 495px; right: 0px; top: 0px; position: absolute; z-index: 3; } .rightcurtain img, .leftcurtain img{ width: 100%; height: 100%; } .logo{ margin: 0px auto; margin-top: 150px; } .rope{ position: absolute; top: -40px; left: 70%; z-index: 4; } </style> </head> <body> <div class="leftcurtain"><img src="images/frontcurtain.jpg"/></div> <div class="rightcurtain"><img src="images/frontcurtain.jpg"/></div> <img class="logo" src="images/buildinter.png"/> <a class="rope" href="#"> <img src="images/rope.png"/> </a> </body> </html> ----------------------------------------------------------------- Any help will be greatly appreciated. Thanks. Jet. Hello All, This is my first post here, so hopefully I don't make to big an *** out of myself. Anyway, I am working on a small 2D game in javascript, and have character movement bound to the onkeydown event. The problem is, that there is a momentary delay between pressing the key, and then it realizing you are still holding it down. So it's Move->stop->Move smoothly You can see what I'm talking about here http://www.digitalswordsmen.com/at/townmap.cfm I know that the delay is happening at the operating system level (you see the same kind of delay if you open up notepad and hold down a letter key, first letter appears instantly, then a short delay before continuing). I was wondering if anyone has a possible solution though, or someway I could smooth out that delay. Also, the walking animations only seem to work in firefox. I guess IE doesn't play animated gifs while the onkeydown even is being fired. Not sure if there is a fix for that, other than animating the individual frames with JS, but that would be pretty laggy I think. Anyway, any input is appreciated. You can see all the code by of course just viewing source, its still fairly simple at this point. Thanks in advance. 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. 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 ! 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> I have a script to call upon a random link every time the page is visited. What I can't figure out is how to delay this loading by 1 or two seconds.. it changes the page as soon as the page is loaded. How would I go about delaying this code for a second or two? +rep to anybody that helps me solve this, thanks. Code: <script> var randomlinks=new Array() randomlinks[0]="http://www.google.com" randomlinks[1]="http://www.yahoo.com" randomlinks[2]="http://www.bing.com" function randomlink(){ window.location=randomlinks[Math.floor(Math.random()*randomlinks.length)] } //--> </script> Hey all, I have a couple of videos that display on web page. I want one to display 5 seconds after another when someone clicks a link. Now I know of the setTimeout method, but I can't seem to get it to work in this below code. The thing is both of the video elements are in the same function. Any help will be greatly appreciated: Code: <script type="text/javascript"> <!-- window.onload = initLinks; var myVid = new Array("area2d.swf","Bar2D.swf", "Column3D.swf", "Column2D.swf"); var myFlash = new Array("data/Area2D.xml","data/Bar2D.xml", "data/Column3D.xml", "data/Column2D.xml"); var thisVid = 0; function initLinks() { document.getElementById("vid1").onclick = processVid1; document.getElementById("vid2").onclick = processVid2; document.getElementById("vid3").onclick = processVid3; document.getElementById("prevLink").onclick = processPrevious; document.getElementById("nextLink").onclick = processNext; } function processVid1() { document.getElementById("myVideo").src = myVid[0]; document.getElementById("myVideo").dataURL = myFlash[0]; document.getElementById("myVideo2").src = myVid[1]; document.getElementById("myVideo2").dataURL = myFlash[1]; return false } function processVid2() { document.getElementById("myVideo").src = myVid[2]; document.getElementById("myVideo").dataURL = myFlash[2]; document.getElementById("myVideo2").src = myVid[3]; document.getElementById("myVideo2").dataURL = myFlash[3]; return false } function processVid3() { document.getElementById("myVideo").src = myVid[2]; return false } function processPrevious() { if (thisVid == 0) { thisVid = myVid.length; } thisVid--; document.getElementById("myVideo").src = myVid[thisVid]; return false; } function processNext() { thisVid++; if (thisVid == myVid.length) { thisVid = 0; } document.getElementById("myVideo").src = myVid[thisVid]; return false; } --> </script> </head> <body> <div id="slideshow"> <h1>Introducing</h1> <table width=""> <tr> <td> <embed src="area2d.swf" flashVars="&dataURL=data/Area2D.xml&debugMode=0&chartWidth=295&chartHeight=295" quality="high" width="295" height="295" type="application/x-shockwave-flash" allowScriptAccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer" id="myVideo" /> </embed> <td <td> <embed src="Bar2D.swf" flashVars="&dataURL=data/Bar2D.xml&debugMode=0&chartWidth=295&chartHeight=295" quality="high" width="295" height="295" type="application/x-shockwave-flash" allowScriptAccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer" id="myVideo2" /> </embed> <td </tr> </table> </div> <div id="pageTree"> <ul> <li><a href="video1.html" id="vid1">Area</a></li> <li><a href="video2.html" id="vid2">Bar</a></li> <li><a href="video3.html" id="vid3">Inventory</a></li> </ul> </div> <div align="center"> <h2><a href="previous.html" id="prevLink">« Previous</a> <a href="next.html" id="nextLink">Next »</a></h2> </div> </body> I have an AJAX search bar what searches after each keyup, but id like to make it so it runs the search if theres a certain delay after the keyup so if you search "hello" it doesnt run 5 times, only once (because there wont be a half a second gap between each letter. Sorry if that doesn't make sense >.<, im just curious if 1) thats possible, 2) what i need to look at to get this to work. Thanks Hi,there, my following script generates random numbers and if random number==1 the background color of textbox="red"; so far it works fine.. What I m tring to do is to tell my script to write amessage in the same textbox after 5 seconds so ı need a delay function.. thanks for help PHP Code: <body bgcolor="pink"> <script> stopx=setInterval("gox()",500); function gox() { var box1=document.getElementById("box1"); var box2=document.getElementById("box2"); box1.value=Math.floor(Math.random()*5); if(box1.value==1) box2.style.backgroundColor="red"; ////////////// // I need a delay function here; // ////////// //???// if(delay==5) box2.value=" 5 seconds passed ,now I will give another message"; } </script> <input type="text" id="box1" style="position:absolute;top:50px;left:20px;width:40px;height:20px;"> <input type="text" id="box2" style="position:absolute;top:50px;left:200px;width:200px;height:50px;"> <input type="button" value="try again" onclick="location.reload()" style="position:absolute;top:250px;left:20px;width:60px;height:50px;"> Hello, I am making a coupon for my mobile website that has to have a response within 60 seconds or so (I would like to be able to play with the time too). This code works but I need to delay the countdown running for a for say 15 seconds after tthe page loads so the people who see the page can read it. Also I would like to know if there is a way I can redirect the page if they do not respond within the countdown time that would go back to the mobile site home page. Also If they leave the coupon page and then go back to the coupon page could I make it so the countdown would still be running as if they never left. I am including the code for the coupon. Almost forgot, can the countdown numbers be red and underlined? Thanks in advance P.S. I don't know much javascript (enough to get in trouble) I searched all over for a solution (till my eyes felt like hemeroids) without bugging you about it. <body> <table cellpadding="3" cellspacing="0" style="width: 320px; height: 480px;"> <!-- MSTableType="layout" --> <tr> <td style="height: 480px; width: 320px;" valign="top" class="style1"> <strong class="style3"><span class="style2">Free Gift ! Plus A $25.00 Discount Off Any Repair $100 Or More!!<br /> </span></strong><br /> That's Right, Get a Free Gift With Your 1st Visit! Plus just for trying us out we'll give YOU $25 off if you spend $100 or more! <br /> <br /> The only catch is you need to respond by calling us within 60 seconds!<br /> <br /> <script type = "text/javascript"> /*author Philip M. 2010*/ function setTimeout("countdown", 20000); var timeInSecs; var ticker; function startTimer(secs){ timeInSecs = parseInt(secs)-1; ticker = setInterval("tick()",1000); // every second } function tick() { var secs = timeInSecs; if (secs>0) { timeInSecs--; } else { clearInterval(ticker); // stop counting at zero // startTimer(60); // remove forward slashes in front of startTimer to repeat if required } document.getElementById("countdown").innerHTML = secs; } startTimer(60); // 60 seconds </script> <span>Remember the Clock is Ticking!</span><br /><span id="countdown" style="font-weight: bold;">You Have <span class="style2"> <u><red>60</red></u></span> Seconds Left.</span> </td> </tr> </table> </body> </html> |