javascript if not click a button within certain time, show some message, settimeout and if logic | XM Community
Skip to main content

Hi, I want to write some javascript: after 30 seconds, the screen shows a button, which needs to be clicked within 10 seconds. If it is clicked within 10 seconds, we show the message "Msg" and next button. If not, we show a "miss message" and automatically click the next button.
I guess this uses settimeout function and if logics. The "miss message" shows even if the button is clicked within 10 seconds. I used 'alert' to check, if the button is clicked, the variable is set to 1, but the "miss message" still shows. Why?

Here are my javascript:

Qualtrics.SurveyEngine.addOnReady(function()
{
  /*Place your JavaScript here to run when the page is fully displayed*/
   
jQuery("#Msg").hide();
jQuery("#MissMsg").hide();
jQuery("#SvcButton").hide();
jQuery("#NextButton").hide();   
var x_val=0; // set this variable equal to 0

// After 30 seconds, show the button that needs to be clicked within 10 seconds
setTimeout(function(){
jQuery("#Button").show();

// if click the button, show the next button
jQuery('#Button').on('click', () => {
jQuery("#Msg").show();
jQuery("#NextButton").show();
var x_val=1; // set this variable equal to 1
});

// after ten seconds, hide timer, show MissServiceMessage
setTimeout(function(){
if (x_val==0){
jQuery("#MissMsg").show();
jQuery("#NextButton").click();
}
}, 10000);
}, 30000);
});

x
is not accessible outside the click handler due to scoping.
Define it outside and set its value inside, and things should work fine.


https://www.qualtrics.com/community/discussion/comment/37582#Comment_37582Hi, I already defined it outside, see line 5 "var x_val=0; // set this variable equal to 0". I set its value equal to 1 if the button is clicked, in the click handler. And later I wanna use this variable in the if logic.


Read up on scoping in javascript.


https://www.qualtrics.com/community/discussion/comment/37620#Comment_37620can u suggest any helpful website? or where am I writing it wrong?


the mistake you are making is really simple, but I don't want to provide you with an answer as it involves a fundamental concept, and if you intend to use js in the future, it should be clear to you.
Just search for scoping in javascript.


https://www.qualtrics.com/community/discussion/comment/37623#Comment_37623I have been searching for the answer all day honestly. I won't post my question here if I can solve it. And your answer is not helping. I understand i need a global variable and i need function to set it. If I know how to write js, i won't ask


https://www.javascripttutorial.net/javascript-variable-scope/


Hi cm201623! We'd recommend checking out W3Schools as a great resource for getting started with custom code. We also have our pages on Adding Custom CSS and Adding JavaScript to help out! 😁


Leave a Reply