I like to know if there will be any performance issue if an xmlhttp
object is created every time. For example, in the below code:
function currentTime(){
var obj = null;
if(window.XMLHttpRequest){
obj = new XMLHttpRequest();
} else {
obj = new ActiveXObject("Microsoft.XMLHTTP");
}
obj.open("GET", "current_time.php", true);
obj.send(null);
obj.onreadystatechange = function(){
if(obj.readyState == 4 && obj.status == 200){
var element = document.getElementById("current_time");
element.innerHTML = obj.responseText;
}
};
}
setInterval("currentTime();", 1000);
or
var obj = null;
function createObj(){
if(window.XMLHttpRequest){
obj = new XMLHttpRequest();
} else {
obj = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function currentTime(){
obj.open("GET", "current_time.php", true);
obj.send(null);
obj.onreadystatechange = function(){
if(obj.readyState == 4 && obj.status == 200){
var element = document.getElementById("current_time");
element.innerHTML = obj.responseText;
}
};
}
createObj();
setInterval("currentTime();", 1000);
In the first example, the XMLHttpRequest
object is created every time (1 sec).
In the second example, the object is created once.
setInterval(currentTime, 1000);
to pass the function reference and avoid implicit eval. – Scimonster Aug 17 at 13:31