JavaScript on Loop

So you want javascript to do something repeatedly at a set interval forever? Easy.

Let’s say I’ve got a function called repeatMe(). I want this to be called every 3 seconds. I do it like this:

setInterval("repeatMe()", 3000);

3000 is the delay in milliseconds. We might want to stop this at some point though, so it’s better to assign this to a variable so that we can refer back to it later. Something like this:

myHandler = setInterval("repeatMe()", 3000);

So now we can assign the following code to, for example, a button:

clearInterval(myHandler);

How about just delaying something so that it happens 3 seconds after it’s supposed to happen? Let’s say I’ve got a function called inabit(). I could assign the following code to a button:

setTimeout(inabit(), 3000);

The inabit() function would be called 3000 milliseconds after the button was clicked.

What about if you clicked the button and in the 3 seconds between it being clicked and the function being called you realise that you don’t want to call the function? Well it’s a bit late now, you’ve already clicked the button. Maybe just close the browser window? In an ideal world you would have planned ahead and made another button which uses the ClearTimeout() function. Bear this in mind when coding your next JavaScript ICBM launcher programme.

Advertisements

About Mr Chimp

I make music, draw pictures, browse the internet, programme, and make sweet, sweet cups of tea until the early hours.
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s