I have issues with setTimeout() function in Javascript.. I want to display seconds in div with id = time.. But setTimeout() is not working properly because the updation is not done in exactly 1 second.. refresh() is an AJAX request function..
var time = 0;
var url = "";
var tm = 0;
var resp = -1;
function refresh(){ // onload refresh is called();
if(tm == 0){
url = "quizload.php";
}
else{
url = "quizload.php?ans=" + resp;
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) {
var a = this.responseText;
var result = JSON.parse(a);
document.getElementById("question").innerHTML = result[0];
document.getElementById("op1").innerHTML = result[1];
document.getElementById("op2").innerHTML = result[2];
document.getElementById("op3").innerHTML = result[3];
document.getElementById("op4").innerHTML = result[4];
time = result[6] == '1' ? 20 : result[6] == '2' ? 35 : 60; // time = 20
}
};
xhttp.open("GET", url, true);
xhttp.send();
tm++;
if(tm == 11){
location.href = "result.php";
}
update();
}
function update(){
setTimeout(function(){
document.getElementById("time").innerHTML = time; // Updation is not exactly 1 second
time = time - 1; // time is is seconds and value is 20
if(time == 0){
refresh(); // Ajax request function
}
update();
},1000);
}
What am I doing wrong here?