...

View Full Version : Javascript delay issue



spman
11-03-2012, 11:40 AM
Hi all - I am struggling to get some code working. What I want is the following :

1. There is a hidden div (basically just a block) on a page.
2. When the user presses an on screen <button> the div appears, turns blue, there is a 3 second delay and the div then dissapears again.

What I am guessing is happening with my code is that it is all working but there is no ouput to the document until the very end of the script by which time the div has been turned to display:none again?

Can anyone suggest the best way of doing this please?

Here is the example code :



<html>
<head>
<script type="text/javascript">
function pause(ms) {
ms += new Date().getTime();
while (new Date() < ms){}
}
function show() {
var b1=document.getElementById("bar1");
b1.style.backgroundColor="blue";
b1.style.display="block";
pause(3000);
b1.style.display="none";
}
</script>
</head>
<body>
<button name="test" onclick="show();">Press Me</button><br>
<div id="bar1" style="display:none; width:50px; height:40px;border:0px;"></div>
</body>
</html>

vwphillips
11-03-2012, 11:50 AM
<html>
<head>
<script type="text/javascript">

function show(id) {
var b1=document.getElementById(id);
b1.style.backgroundColor="blue";
b1.style.display="block";
clearTimeout(show[id]);
show[id]=setTimeout(function(){ b1.style.display="none" },3000);
}
</script>
</head>
<body>
<button name="test" onclick="show('bar1');">Press Me</button><br>
<div id="bar1" style="display:none; width:50px; height:40px;border:0px;"></div>
</body>
</html>

spman
11-03-2012, 12:05 PM
That's great Vic - works a treat - Now I just need to work out what it's doing :)

(i'm pretty new to Javascript) - What is the significance of passing the parameter (id) to the function and what do the square brackets signify please?

vwphillips
11-03-2012, 12:20 PM
<html>
<head>
<script type="text/javascript">

function show(id,c) {
var b1=document.getElementById(id);
b1.style.backgroundColor=c;
b1.style.display="block";
clearTimeout(show[id]);
show[id]=setTimeout(function(){ b1.style.display="none" },3000);
}
</script>
</head>
<body>

passing the id allows multiple applications of the script.<br />
<br />
when using setTimeout it is good practice to clear the timeout before use.<br />
this can be done by assigning the timeout to a global variable<br />
but global variables should be avoided<br />
so a property of function show(show['bar1'] = show.bar1) is used.<br />
<br />
<button name="test" onclick="show('bar1','blue');">Press Me</button><br>
<div id="bar1" style="display:none; width:50px; height:40px;border:0px;"></div>

<button name="test" onclick="show('bar2','red');">Press Me</button><br>
<div id="bar2" style="display:none; width:150px; height:40px;border:0px;"></div>
</body>
</html>

spman
11-03-2012, 12:33 PM
Thank you for the concise explanation Vic - Very very helpful :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum