Advertise Here

Author Topic: Learn how to use the SetInterval() function  (Read 3938 times)

0 Members and 1 Guest are viewing this topic.

Offline slayer766

  • SMF For Free Full Member
  • *
  • Posts: 212
    • View Profile

  • Total Badges: 13
    Badges: (View All)
    Topic Starter Combination Level 3 Level 2 Level 1
Learn how to use the SetInterval() function
« on: February 04, 2008, 07:27:57 pm »
This tutorial is all about the function setInterval() It works kinda like setTimeout() but instead of the function being executed once and only once, setInterval() executes the function forever until you clear it. So I will show you an example of setInterval():


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

function Get_It(){
setInterval('alert("I\'m annoying...")',5000);
}
GetIt();
</script>

Yes that will get very annoying if it were to be an actual code that someone used without it being cleared at some point. Which what I wrote will always alert every 5 seconds. ;)



You could use setInterval() to maybe create text effects or make a slide show. I will show you something to the extent of text effects:

Code: [Select]
<a href='javascript:Start_It();'>Start the effects</a><br /><a href='javascript:Stop_It();'>Stop the effects</a><br /><br /><span id="effect">This is some text</span><br />

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

function Start_It(){
it_is = setInterval('Effects();',2000);
}

function Effects(){
document.getElementById("effect").style.color="red";
setTimeout('Effects2();',500);
}

function Effects2(){
document.getElementById("effect").style.color="green";
}

function Stop_It(){
clearInterval(it_is);
}

</script>

Alright what I did was just basically run the Interval every 2000 milliseconds, or 2 seconds, have it start a function to color the text. The put in a setTimeout function to initiate at 500 milliseconds, or 1/2 a second to color it a different color. Then since the Interval function is always going to be running it will color the text red again, and keep on doing that until you click Stop the effects. Which in that function I clear the Interval. Remember that clearing an Interval you must always assign it to a variable, otherwise the function will not know what to clear. ;)
« Last Edit: February 04, 2008, 07:29:34 pm by slayer766 »

 

Related Topics

  Subject / Started by Replies Last post
0 Replies
5909 Views
Last post February 04, 2008, 07:27:04 pm
by slayer766
0 Replies
3276 Views
Last post February 04, 2008, 07:28:49 pm
by slayer766
3 Replies
3644 Views
Last post June 04, 2008, 11:26:18 pm
by guest4485
11 Replies
5182 Views
Last post July 17, 2008, 04:48:26 pm
by LaundryLady
1 Replies
7338 Views
Last post December 14, 2011, 10:30:04 pm
by SMF For Free