Alucard
Alucard

Reputation: 1902

Execute Js code until the document is ready

What's the best way to keep executing a JS code (each 100 ms in m case) until the document is ready.

setInterval(function() { 
   xajax_updateLoader();
}, 100);

One the document is ready. The execution should stop.

Upvotes: 0

Views: 89

Answers (5)

Amit Soni
Amit Soni

Reputation: 1427

var updateInterval;
$(function(){
 updateInterval= setInterval(function() { 
   xajax_updateLoader();
}, 100);
});

$(windows).load(function(){
    clearInterval(updateInterval)
});

Upvotes: 2

Use clearInterval()

var interval = setInterval(function() { ... }, 100);
$(document).ready(function(){
 clearInterval(interval);
});

Upvotes: 1

Paul Rad
Paul Rad

Reputation: 4882

Like this

domReady = false;

var ctx = setInterval(function() {
 if (domReady === true)
 {
  clearInterval(ctx);
 }
 // your code here
}, 100);

if (typeof document.addEventListener !== 'undefined') // chrome / safari / firefox
{
 document.addEventListener("DOMContentLoaded", function(){
  domReady = true;
  document.removeEventListener('DOMContentLoaded');
 }, false);
}
else if (typeof document.attachEvent !== 'undefined') // IE
{
 document.attachEvent("onreadystatechange", function(){
  if ( document.readyState === "complete" )
  {
   document.detachEvent( "onreadystatechange", arguments.callee );
   domReady = true;
  }
 });
}

Upvotes: 1

Johan
Johan

Reputation: 35223

var handle = setInterval(function() { 
   xajax_updateLoader();
   if (jQuery.isReady) {
       //DOM is ready
       clearInterval(handle);
   }
}, 100);

Upvotes: 1

Simon Fischer
Simon Fischer

Reputation: 1208

var interval = setInterval(function() { ... }, 100);
window.onload = function() { clearInterval(interval); }

This clears the interval on the onload event.

Upvotes: 1

Related Questions