Stopping timer at end of block using javascript | XM Community
Skip to main content

Hi everyone,
I have used the below code to successfully start a countdown timer within a block of code using the survey flow to create embedded data. The timer does stop at the end of the countdown. However, I need to start a second timer in a subsequent block and stop the first timer for those who finish the first block early. That is if participants finish the first block before time expires, I need to clear the first timer prior to them moving to the next block where a new timer would start. Any assistance would be greatly appreciated.

Qualtrics.SurveyEngine.addOnload(function()
{
 var header = document.createElement("div");  
 header.className = "header"  
 header.id = "header_1";  

var timer = document.createElement("div");  
 timer.className = "timer";  
 timer.id = "timer_1";  
 timer.innerHTML = "Time Remaining: 25:00"; 

header.appendChild(timer);
document.body.insertBefore(header, document.body.firstChild);

function startTimer(duration, display) {  
 var timer = duration, minutes, seconds;  
 var myTimer = setInterval(function() {  
    Qualtrics.SurveyEngine.setEmbeddedData('TimeRemaining', timer);
  minutes = parseInt(timer / 60, 10)  
  seconds = parseInt(timer % 60, 10);  
  minutes = minutes < 10 ? "0" + minutes : minutes;  
  seconds = seconds < 10 ? "0" + seconds : seconds;  
  var text = ('innerText' in display)? 'innerText' : 'textContent';
  displaystext] = minutes + ":" + seconds;  

  if (--timer < 0) {  
  clearInterval(myTimer);  
  timeOver();  
  }  
 }, 1000);  
 }  
var timerSeconds = parseInt("${e://Field/TimeRemaining}");  
 display = document.querySelector('#time');  
 startTimer(timerSeconds, display);  
 var timeOver = function() {  
 document.getElementById("timer_1").innerHTML = "Time is up.";  
   $('NextButton').click();
 }  
});

Before your other block. Set the TimeRemaining embedded variable to the time you want to give for that block


Leave a Reply