Hi, My multiple choice code works fine, except it executes the new/next question too fast. I tried to set a delay so there is at least 2 seconds until the next question is loaded, but setTimeout(function(){return_next_question;}, 2000); doesn't seem to wait until it calls the value of return_next_question.
What's going on?
Thanks.
Code:
var return_next_question = $("#ajaxArea").load("ajax-part.php");
function next_question() {
// Sets value for return_next_question while user is reading current one
return_next_question = $("#ajaxArea").load("ajax-part.php");
}
function checkAnswer(id, value) {
var button_id = document.getElementById(id);
if (value == 0) {
...Some stuff happens
setTimeout(function(){return_next_question;}, 2000);
} else { // value == 1 and answer is correct
...Some stuff happens
setTimeout(function(){return_next_question;}, 2000);
}
// Prepare the next_question() while user is reading current one
next_question();
}
setTimeout(next_question, 2000); would show the next question after two seconds. The setTimeout calls you have right now don't do anything at all (you're just saying return_next_question without actually doing anything with the variable), and also you're calling next_question() at the end of the checkAnswer function which of course will load and show the next question right away.
Ah, I see. Thanks. I was trying to somehow cache the next question so there would be no extra load time after the delay, but thanks for clearing that up. The delay, at least works well now
Maybe you could load all questions at page load? That would reduce server bandwidth usage and remove any extra waiting time between the questions.
Otherwise you'd have to use another method than using $.load() which put the loaded content into the element as soon as the requested data is received. I think $.get() is what you're looking for in that case - to fetch data from the server without inserting it right away. You could use that function together with a timeout and either make the get() or the timeout show the next question (whichever takes the longest time).
Code:
var timeoutDone = false;
var ajaxData;
setTimeout(function(){
if (ajaxData)
$("#ajaxArea").html(ajaxData);
timeoutDone = true;
}, 2000);
$.get('ajax-part.php', function(data) {
if (timeoutDone)
$("#ajaxArea").html(data);
else
ajaxData = data;
});
Bookmarks