Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

if statement problem in Ajax

Hi, I am making a website where depending on what a column says in the database the javascript will perform a curtain task (using ajax). This is going fine, however in the if statement, when the requirements are met, it keeps repeating it since it's inside the setInterval. It is probably easier for me to just paste the code and give you a chance to take a look at it.

    setInterval(function(){

        $("#div").load("content.php");

        if ($('#div:contains("hello")').length > 0) {
            alert("Hello, world!");
        }

    }, 200);

As you can see above, the alert is alerted forever at the speed the interval is set to, please help.

Seth Kroger
Seth Kroger
56,403 Points

I think it would be best to first ask yourself when you when you want the if clause to run. Do you want it to run just once? Whenever the result changes? Then you'll have 2 conditions to check: does it contain "hello" and have I run this before/has the value changed from last time?

How would I write those conditions in code?