SMF For Free Support Forum

General Stuff => Programming => JavaScript => Topic started by: slayer766 on February 04, 2008, 07:28:49 pm

Title: Learn how to use the SetTimeout() function
Post by: slayer766 on February 04, 2008, 07:28:49 pm
Alright in this tutorial I am going to explain to you on how we can use JavaScript's setTimeout() function. This is essential for setting up other options to function at a specific time. This could be an onload function, or it could happen when you click a button. I will show you an example of an onload function for the setTimeout() function.


First we start with our body onload to start the function:

Code: [Select]
<body onload="Timed();">

Now that we have our function, this will be called when the body of the page has loaded completely. So we now would set a function inside of <script> tags to initiate the Timed() function:


Code: [Select]
<script type="text/javascript">

function Timed(){
setTimeout('alert("Hello there!")',4000);
}

</script>


Ok you see it's just one line of code, very basic function. The first bit is what you want the function to do in the alloted time. Which the alloted time is 4000, this being in milliseconds, would be 4 seconds. ;)


Another example of setTimeout could be this:

Code: [Select]
<span id="show">Wow...this is unique.</span>
Code: [Select]
<script type="text/javascript">

function Timed_2(){
setTimeout('Display();',2000);
}

function Display(){
document.getElementById("show").innerHTML+="<br />Hello there!";
}


What this will do is add "Hello there!" onto "Wow...this is unique". This will happen in the specified time in milliseconds which was 2000, or 2 seconds. :)



So the setTimeout() function will execute anything in its parameters in the amount of specified time.