Jump to content

setInterval freezes but works when reloaded


Lingo

Recommended Posts

Hello so I am using a setInterval to query an ajax to PHP script that returns a number which depending on the number will make a div appear on screen.

 

However the setInterval freezes and does nothing unless I refresh the page in which it then appears.

 

Code:

 

 

 

 
<div id="invisable">

<font color="red">You have a new message! <a href="inbox.php">Click here</a> to go to messages.</font>

</div>

<script type="text/javascript">
function getXMLHttp()
{
  var xmlHttp

  try
  {
    //Firefox, Opera 8.0+, Safari
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    //Internet Explorer
    try
    {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
      try
      {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch(e)
      {
        alert("Your browser does not support AJAX!")
        return false;
      }
    }
  }
  return xmlHttp;
}

function MakeRequest()
{
  var xmlHttp = getXMLHttp();
 
  xmlHttp.onreadystatechange = function()
  {
    if(xmlHttp.readyState == 4)
    {
      HandleResponse(xmlHttp.responseText);
    }
  }

  xmlHttp.open("GET", "getmessages.php", true);
  xmlHttp.send(null);
}

function HandleResponse(response)
{

if(response==1){
  document.getElementById('invisable').style.display="block";
    }
 
  }
setInterval(MakeRequest(),1000);
</script>

 

setInterval is set to every second...

 

I don't know why it freezes please help

 

Thanks,

Lingo

You're not using referencing your MakeRequest function correctly. By having the () after MakeRequest, you are executing it NOW, and passing it's return value (which is undefined) into setInterval. What you actually want to be doing is passing the function itself in as the argument for setInterval that way it will be executed each time setInterval ticks. You do that by using only the function name, no () after it.

setInterval(MakeRequest, 1000);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.