Skip to page content or Skip to Accesskey List.

Work

Main Page Content

Using Setinterval To Make A Javascript Listener

Rated 3.63 (Ratings: 10)

Want more?

  • More articles in Code
 
Picture of pixelmech

Tom Dell'Aringa

Member info

User since: 20 May 2002

Articles written: 1

Oftentimes when you are building something, you need some kind of function to "listen" for either an event or a condition. You need this to happen continously so you can act upon it when it does happen.

Quite often programmers attempt to use setTimeout() in these cases, which isn't what you want. What you need is the red-headed stepchild (apologies to redheads) of setTimeout(), setInterval().

Often if you mention setInterval() to somebody, they reply one of two ways:

  1. You mean setTimeout()? or
  2. Huh?

I'm not sure why this is - maybe too many "cut and paste" scripts out there with setTimeout() in them. Anyway, there is a vast gulf of difference between the two, and the gulf is very simple to understand.

  • setTimeout() allows you to DELAY the execution of an expression or evaluate a function.
  • setInterval() allows you to EVALUATE an expression or a function at set INTERVALS (thus the name - neat eh?).

So, who cares about setTimeout(), we've all heard enough about that. Let's have a bash at an example.

The Need

Your mission, should you accept it: you have two text input boxes. When text is entered into both fields, you want to display a hidden div. You can't do this on the submission of the form, because the hidden div contains more input that has to be sent along with it. (Play along, it's just an example!)

What you need to know is when both fields have entries. (We won't worry about error checking, etc.) This is where our buddy setInterval() comes in.

Our Page Code:

<html>

<body>

<form id="form">

<input type="text" id="text1">

<input type="text" id="text2">

<div id="hidden" style="display: none;"><input type="text" id="text3"></div>

<input type="submit" value="submit">

</form>

</body>

</html>

First, Our Function

First, we need a function to do what we want to happen when our condition is met. What it needs to do is display our hidden block:

function showHiddenDiv()

{

var textBox1 = document.getElementById("text1").value;

var textBox2 = document.getElementById("text2").value;

var ourDiv = document.getElementById("hidden").style;

if(textBox1 != "" && textBox2 != "")

{

ourDiv.display = "block";

return true;

}

return false;

}

We set up some local variables to point to our two text boxes and their values (what's in them) and our hidden div's style. Then we have our condition here - if both text boxes are not equal to empty (they must both be full) we change the display style to block, and it becomes part of the page flow.

If one of the text boxes is still empty, the 'else' condition fires and we return 'false.' You don't have to do this, but I understand its good technique to return some value from your functions, and apparently the strict warnings in some new browsers (if you have the feature turned on) will send you a warning if you don't.

Second, the Interval

Now, we need to set up our interval to periodically fire off our function to do the checking or "listening." The structure for the setInterval() method is:

var interval_name = setInterval([expression_or_function], [time_period]);

And if you use a function, it must be quoted and include the brackets. Now, you don't want to go nuts and check the thing every 10 milliseconds - consider that a Bad Thing(tm) and a performance hit. However, once per second would be fine, and once that second entry is made your hidden div should be showing.

Our Interval Method:

var ourInterval = setInterval("showHiddenDiv()", 1000);

That's it - that's all. Once the page is loaded, showHiddenDiv() will run every second until it's first condition is met, and the hidden div is shown. Great! But then what? How do you stop it? The beauty is, since you set your interval to a variable, that variable is now the id for your interval. All you need is to add the clearInterval() method to your function, with the variable name as its parameter. So your final function looks like this:

function showHiddenDiv()

{

var textBox1 = document.getElementById("text1").value;

var textBox2 = document.getElementById("text2").value;

var ourDiv = document.getElementById("hidden").style;

if(textBox1 != "" && textBox2 != "")

{

ourDiv.display = "block";

clearInterval(ourInterval);

}

else

{

return false;

}

}

Other Issues

Of course in this case, you might have to deal with issues such as, what if the user erased one input and so forth. But that's your job. If the user reloads the page, you're golden, because your script reloads too and your interval restarts.

So tap into the power of setInterval() and "listen" to your heart's content!

Tom got his start in web development in the winter of 1995 when his boss threw an HTML book in his direction stating "we should learn about this world wide web thing." Since then he has worked at dot.com era startups with no real business model, web integrator Scient and lately as a freelance and contracting developer. Experienced in HTML, JavaScript, and CSS as well as server-side scripting languages, he has worked on everything from simple brochure sites to enterprise level portals.

It was during one of these large projects that he finally got fed up with the "IE only" mentality of coding. Additionally, even large corporations seemed unaware of the benefits of separating style from content and still produced bloated, non-standard code. In response to this, and a corresponding discussion on Evolt's thelist, he founded MACCAWS.org in late 2002. MACCAWS is a group of developers seeking to help other developers make the commercial case for using web standards to their clients and bosses. This means showing them that beyond the programmatical and practical benefits, there is also a fiscal benefit as well.

Lately part of his role on teams involves explaining to developers what LABEL tags are, that they shouldn't build layouts with tables nested ten levels deep, showing them alternatives to using 127 spacer gifs per page, proving the benefits of a global stylesheet and defining DOCTYPEs and how to use them.

He realized the dot.com era was over when his paychecks started bouncing right after the big welcome party he had been flown to in San Francisco. He currently resides in the Midwest with his wife and two children. He plays guitar and and even recorded a demo CD with his band. Constantly scouring Ebay and garage sales for Charlie Brown and Snoopy paperbacks, he is finding it very hard to find the Peanuts Parade versions...anyone?

The access keys for this page are: ALT (Control on a Mac) plus:

evolt.org Evolt.org is an all-volunteer resource for web developers made up of a discussion list, a browser archive, and member-submitted articles. This article is the property of its author, please do not redistribute or use elsewhere without checking with the author.