setTimeout simply doesn't work! | XM Community
Solved

setTimeout simply doesn't work!

  • 1 February 2019
  • 2 replies
  • 25 views

Badge +2
I am designing an experiment in qualtrics using java script. For each question in my study, a participant needs to guess the correct answer, type it in, and then hit the space button. Once they hit the space button, a logic checks whether their answer is correct or not. If the answer was correct, a sound should be played for 1.2 seconds, the background color should change into red for a second and then back to white, and lastly the experiment should automatically moves on to the next question.

It seems like i am not using the setTimeout logic correctly. no matter what combination of timeout values I used, I couldn't get it to play all the middles steps, including the audio play and red background flash, before the screen moves to the next question. Currently, she background flashes red for less than a second and the screen moves on to the next question. The audio sound simply gets skipped. Even if I change the 2000 an 3000 to 5000 and 8000, still the same result. It is as if these numbers don't mean anything!.

I've been spending two days on this and still no progress. If this is a known bug, please let me know. Otherwise, please please help me to figure out what I am doing wrong.

Here, I 've shared my code. I would very much appreciate any help.


Qualtrics.SurveyEngine.addOnload(function()
{
/*Place your JavaScript here to run when the page loads*/
});

Qualtrics.SurveyEngine.addOnReady(function()
{
/*Place your JavaScript here to run when the page is fully displayed*/

var qid = this.questionId;
var changepage = null;

/*focus on the box*/
jQuery("#"+qid+" .InputText").select().focus();

document.onkeydown = function(event) {
console.log('keydown',event);
if (event.which == 32) { //hit the space button
event.preventDefault();
//read the input
input = jQuery("#"+qid+" .InputText").val();
console.log(input);

if (input.trim().toLowerCase() == "cat") {

//alert(input.trim().toLowerCase());
document.getElementById("correct").play(); //play the correct sound which is 1.2seconds long

setTimeout(jQuery("body").css("background-color","red"), 2000); // change the background color

setTimeout( jQuery('#NextButton').click(), 3000) //move on to the next question

} //end of if
} // end of if 32
} //end of down button

});

Qualtrics.SurveyEngine.addOnUnload(function()
{
jQuery("body").css("background-color","white");
});
icon

Best answer by TomG 2 February 2019, 00:53

View original

2 replies

Userlevel 7
Badge +27
Check to make sure the only element with the id correct is your audio. You should add an 'ended' event to your audio, and execute the background change to red (with no setTimeout), and the click Next with SetTimeout within the 'ended' event.

You shouldn't use "body", use ".Skin" instead. Then you don't need the addOnUnload at all.
Badge +2
Thank you TomG I fixed it.

Leave a Reply