Jump to content

setInterval freezes but works when reloaded


Lingo
Go to solution Solved by kicken,

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

Link to comment
Share on other sites

  • Solution

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);
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.