0

I have an html structure as shown below also have AJAX API which refresh the span inside the third div asynchronously. I want to check the content of span inside div3 repeatedly which is added dynamically by API. If it contains 'Hi' I want to display image inside div3 otherwise display nothing.

<div id="div1">
  <div id="div2">
   <div id="div3">
       <span>Hi</span>
   </div> 
  </div>
</div>

<script type="text/javascript">
         $(function(){
          (function loopsiloop(){
            setTimeout(function(){
            var tmp = $('#div3').find("span").val();
            if(tmp=='hi'){
            document.getElementById("myChatLinkInfo").innerHTML ='<img src="http://slovnikonline.com/img/hi-ohio-logo.jpg">';
            }
            loopsiloop();
        },4000);
    })();
loopsiloop();
         });
</script>
Darpit
  • 33
  • 4

1 Answers1

1

There are two ways to repeat a function: setInterval() and setTimout( // call fn inside itself ).

From my experience, the 2nd way is best because if something interferes with the setInterval function, it won't adjust its timing correctly -- over time, you can end up with 100% browser usage (basically a frozen app) as setInterval attempts to catch up. See:

setTimeout or setInterval?

http://www.erichynds.com/blog/a-recursive-settimeout-pattern


Your code would look something like this:

$(function(){
    (function loopsiloop(){
        setTimeout(function(){

            //AJAX below
            var tmp = $('#checkme').val();
            $('#freshme').text(tmp);
            //AJAX ABOVE

            loopsiloop();
        },4000); // <=== 4 sec delay
    })();

    loopsiloop();

}); //END document.ready

jsFiddle Demo


Here are some posts for getting the basics of AJAX:

A simple example

More complicated example

Populate dropdown 2 based on selection in dropdown 1

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • Hi gibberish, I have updated my post with the code provided by you. But its not working as per the expectation any help wold be highly appreciated. – Darpit Mar 13 '15 at 08:35
  • Break the problem into steps. First, get the loop `loopsiloop` function working, exactly like in the jsfiddle, but on your site -- just using an input field, exactly like my example. Then, put that aside, and get your ajax working - on demand, using a button. So that when you press the button, the ajax fires. **See updated answer for links to super-easy AJAX examples - study them!** Third and finally, put the two together. *But get them working independently, first.* – cssyphus Mar 13 '15 at 13:50