Neil Porven
Neil Porven

Reputation: 83

Ajax setInterval causing browser to be unresponsive

I have the following test code:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ajax - one variable test</title>
 <style>
   body{ font-size: 12px; font-family: Arial;}
 </style>

<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<ol id="variable1"><var1></ol>

<script>
setInterval(function()
 {
  $("#variable1").load("ajax_v00.html")
 },3000);
</script>


</body>
</html>

I am using an embedded web-server that reports a status to var1.

example: Ok or Head Up

The above is crashing any browser that I tested on. Can someone see if I am doing something wrong?

Thank you.

Upvotes: 0

Views: 1349

Answers (1)

Salketer
Salketer

Reputation: 15711

The request might take more than 3 seconds to execute thus stacking the requests until the browser cannot handle it all and crash... Instead of using an interval, you should use a timeout that will execute the request 3 seconds AFTER the last one finished. Here:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ajax - one variable test</title>
 <style>
   body{ font-size: 12px; font-family: Arial;}
 </style>

<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<ol id="variable1"><var1></ol>

<script>
function doRefresh()
 {
  $.ajax({
     url:"ajax_v00.html",
     success:function(data){
         $("#variable1").html(data);
         setTimeout(doRefresh,3000);
     }
  });
}
setTimeout(doRefresh,3000);
</script>


</body>
</html>

Upvotes: 2

Related Questions