Stopping timer at end of block using javascript - javascript

I am new to this. I have a Qaultrics survey consisting of different blocks; each block with its own timer. What I want to achieve is the following; if participants complete the first block before the given time, the timer on that block will be cleared as they move to the next block where a new timer would start. In the following block, a new timer needs to start.
Any assistance would be greatly appreciated.
Qualtrics.SurveyEngine.addOnload(function()
{
var headerCont = document.createElement("div");
headerCont.className = "header-cont";
headerCont.id = "header_container";
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: <span id='time'>01:00</span>";
headerCont.appendChild(header);
header.appendChild(timer);
document.body.insertBefore(headerCont, document.body.firstChild);
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var myTimer = setInterval(function() {
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';
display[text] = minutes + ":" + seconds;
if (--timer < 0) {
clearInterval(myTimer);
timeOver();
}
}, 1000);
}
var timerSeconds = 60,
display = document.querySelector('#time');
startTimer(timerSeconds, display);
var timeOver = function() {
document.getElementById("timer_1").innerHTML = "";}
});
Qualtrics.SurveyEngine.addOnUnload(function()
{
clearInterval(myTimer);
clearInterval(timer);
clearInterval(timer_1);
document.getElementById("timer_1").innerHTML = "";
});

Here is what I did;
On the first question I used the following code
```Qualtrics.SurveyEngine.addOnload(function()
{
var headerCont = document.createElement("div");
headerCont.className = "header-cont";
headerCont.id = "header_container";
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: <span id='time'>02:10</span>";
headerCont.appendChild(header);
header.appendChild(timer);
document.body.insertBefore(headerCont, document.body.firstChild);
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var myTimer = setInterval(function() {
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';
display[text] = minutes + ":" + seconds;
if (--timer < 0) {
clearInterval(myTimer);
timeOver();
}
}, 1000);
}
var timerSeconds = 130,
display = document.querySelector('#time');
startTimer(timerSeconds, display);
var timeOver = function() {
document.getElementById("timer_1").innerHTML = "";}
});```
Then in the last question in the block, I used the following code
{
Qualtrics.SurveyEngine.addOnPageSubmit(function() {
Qualtrics.SurveyEngine.setEmbeddedData('timeRemaining',timer);
clearInterval(myTimer); // fairly certain this isn't doing anything
});
});
Qualtrics.SurveyEngine.addOnReady(function()
{
/*Place your JavaScript here to run when the page is fully displayed*/
});
Qualtrics.SurveyEngine.addOnUnload(function() {
document.getElementById("header_container").remove();
});```

Related

Countdown It does not Work on a minute system

I have a simple code but there is a problem
How do I make this code work in a minute and a second system
Tried but only work a second!
You can look at the code
https://jsfiddle.net/o183pdqg/1/
I hope for help because I am really tired and I am looking for a solution
function secondPassed() {
var seconds = 120;
var countdownElement = document.getElementById('countdown');
var contentElement = document.getElementById('content');
var adsElement = document.getElementById('ads');
var minutes = Math.round((seconds - 30) / 60);
var remainingSeconds = seconds;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "";
} else {
seconds--;
}
adsElement.style.display = '';
countdownElement.innerHTML = remainingSeconds;
var interval = setInterval(function() {
countdownElement.innerHTML = --remainingSeconds;
if (remainingSeconds === 0) {
clearInterval(interval);
contentElement.style.display = '';
adsElement.style.display = 'none';
}
}, 1000);
}
<div id="container">
Send Code
<div id="ads" style="display: none">
<div id="countdown"></div>
<div>Sent!</div>
</div>
<div id="content" style="display: none">Error!</div>
</div>
you need to put variable minutes and seconds within setInterval function to make it work. Convert the time var remainingSeconds = seconds * 1000; from second to milisecond so it will make it easier when working with new Date().getTime().
To get minutes and second, try it using modulus (%) operator to get remaining time from your starting time.
var availability = true
function secondPassed() {
if (!availability) {
return false
}
var seconds = 120;
var countdownElement = document.getElementById('countdown');
var contentElement = document.getElementById('content');
var adsElement = document.getElementById('ads');
availability = false
adsElement.style.display = '';
contentElement.style.display = 'none';
function runInterval () {
var remainingSeconds = seconds * 1000;
let minutes = Math.floor(remainingSeconds % (1000*60*60)/ (1000*60));
let seconds1 = Math.floor(remainingSeconds % (1000*60) / 1000);
if (seconds1 < 10) {
seconds1 = "0" + seconds1;
}
document.getElementById('countdown').innerHTML = minutes + ":" + seconds1;
if (seconds == 0) {
// clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "";
} else {
seconds--;
}
if (remainingSeconds === 0) {
clearInterval(interval);
contentElement.style.display = '';
adsElement.style.display = 'none';
availability = true
}
}
var interval = setInterval(function() {
// countdownElement.innerHTML = --remainingSeconds;
runInterval ()
}, 1000);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="container">
Send Code
<div id="ads" style="display: none">
<div id="countdown"></div>
<div>Sent!</div>
</div>
<div id="content" style="display: none">Error!</div>
</div>
</body>
</html>
You can try with this answer
secondPassed = () => {
let remainingSeconds = 120;
const countdownElement = document.getElementById('countdown');
const contentElement = document.getElementById('content');
const adsElement = document.getElementById('ads');
adsElement.style.display = '';
const getPad = (num) => {
return (num < 10) ? '0' + num.toString() : num.toString();
}
const interval = setInterval(() => {
let minutes = Math.floor(remainingSeconds / 60) % 60;
let seconds = getPad(remainingSeconds % 60);
countdownElement.innerHTML = `${minutes} : ${seconds}`;
remainingSeconds--;
if (remainingSeconds == 0) {
clearInterval(interval);
contentElement.style.display = '';
adsElement.style.display = 'none';
}
}, 1000);
}

how to create click event to display set interval time

I have a Javascript setInterval function set up to display like a timer. I'd like to display the time that is on the timer when a "next" button is clicked so the user can see how long they've spent on a certain page. I'm unsure how to connect the setInterval with a click event. This is what I have, but it's not working.
let timerId = setInterval(function () {
document.getElementById("seconds").innerHTML = pad(++sec % 60);
document.getElementById("minutes").innerHTML = pad(parseInt(sec / 60, 10));
}, 1000);
function myFunction() {
alert document.getElementById("timerId").innerHTML = "Time passed: " + timerId);
}
This should solve your problem.
var initialTime = new Date().getTime();
var timeSpent='0:00';
var timeElement = document.getElementById("time");
timeElement.innerHTML = timeSpent;
let timerId = setInterval(function () {
var currentTime = new Date().getTime();
timeSpent = millisToMinutesAndSeconds(currentTime - initialTime)
timeElement.innerHTML = timeSpent;
}, 1000);
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}
function alertFn(){alert(timeSpent)}
document.getElementById("rightButton").addEventListener('click',alertFn);
document.getElementById("wrongButton").addEventListener('click',alertFn);
<h1 id="time"></h1>
<button id="rightButton">Right</button>
<button id="wrongButton">Wrong</button>
First of all, it would be better if you put setInterval method inside the function. After that you could give your function to an event listener as an argument.
Your code should look something like this
let timerId;
function displayTime() {
timerId = setInterval(() => {
// your code
}, 1000);
}
document.querySelector('button').addEventListener('click', displayTime)

Showing Multiple Timers PHP + Javascript

I'm working on having multiple timers run in Javascript with the user data and time remaining pulled from a PHP + MySQL instance
Currently I have the following PHP Code:
<?php
$now = strtotime("now");
$allArrested = $conn->query("SELECT `user_id` FROM `user_jail` WHERE `jail_stop` > '$now'") or die(mysqli_error($conn));
if($allArrested->num_rows > 0){
while($arrested = $allArrested->fetch_assoc()){
foreach($arrested as $jailTime){
$checkTime = $conn->query("SELECT `jail_stop` FROM `user_jail` WHERE `user_id` = '$jailTime'") or die(mysqli_error($conn));
while($letsTime = $checkTime->fetch_assoc()){
$x = $letsTime['jail_stop'];
$letGo = $x - $now;
foreach($arrested as $convict){
echo "<div>".usernameById($convict)." for <span class=\"time\">".$letGo."</span></div>";
}
}
}
}
}
?>
And the following javascript:
<script>
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = 0;
display.textContent = "";
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = <?php echo $letGo; ?>,
display = document.querySelector('.time');
startTimer(fiveMinutes, display);
};
</script>
For testing purposes I have 4 different usernames. Currently only the first one is counting down.
The other 3 users counters remain on 90sec (variable $letGo).
Is anyone able to help me with this?

How can I modify my function to be able to cancel the interval from anywhere in the controller

I am trying to create a countdown and I want to be able to cancel the interval not only when reach 0 but with clicking of a button as well.How can I modify my function to be able to cancel the interval from anywhere in the controller.
function countDown(total) {
total = total * 60;
var interval = $interval(function () {
var minutes = Math.floor(total / 60);
var seconds = total - minutes * 60;
if (minutes < 1)
{
minutes = '0:';
}
else
{
minutes = minutes + ':';
}
if (seconds < 10)
{
seconds = '0' + seconds;
}
self.remainingTime = "Remaining time: " + minutes + seconds;
total--;
if(minutes === '0:' && seconds === '00')
{
$interval.cancel(interval);
}
}, 1000);
}
As suggested by other users, you should make interval global in the controller. Then on the other functions you want to cancel the interval you can call it safely.
Take a look at the below sample:
angular.module('app', [])
.controller('ctrl', function($interval) {
var self = this;
var interval;
self.wizard = {
startInterval: startInterval,
cancelInterval: cancelInterval
};
startInterval();
return self.wizard;
function startInterval() {
countDown(24);
}
function cancelInterval() {
$interval.cancel(interval);
}
function countDown(total) {
cancelInterval();
total = total * 60;
interval = $interval(function() {
var minutes = Math.floor(total / 60);
var seconds = total - minutes * 60;
if (minutes < 1) {
minutes = '0:';
} else {
minutes = minutes + ':';
}
if (seconds < 10) {
seconds = '0' + seconds;
}
self.wizard.remainingTime = "Remaining time: " + minutes + seconds;
total--;
if (minutes === '0:' && seconds === '00') {
$interval.cancel(interval);
}
}, 1000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<span ng-app="app" ng-controller="ctrl as ctrl">
<span ng-bind="ctrl.remainingTime"> </span>
<br/>
Cancel Interval
<br/>
Start Interval
</span>
I created an example using self instead of $scope like you are in your snippet above. As others mentioned moving the interval var to the global scope fixes this. I also added a stop and start function to test the issue you mentioned in the example above.
UPDATED - I added some code to the stop interval to reset the interval to undefined. I found an example of this usage on Angular's site so it might be worth a try to see if it fixes your other issue.
var app = angular.module('app', []);
app.controller('BaseController', function($interval) {
var self = this;
var interval;
function countDown(total) {
total = total * 60;
interval = $interval(function() {
var minutes = Math.floor(total / 60);
var seconds = total - minutes * 60;
if (minutes < 1) {
minutes = '0:';
} else {
minutes = minutes + ':';
}
if (seconds < 10) {
seconds = '0' + seconds;
}
self.remainingTime = "Remaining time: " + minutes + seconds;
total--;
if (minutes === '0:' && seconds === '00') {
$interval.cancel(interval);
}
}, 1000);
}
self.stopInterval = function(){
if (angular.isDefined(interval)) {
$interval.cancel(interval);
interval = undefined;
}
}
self.startInterval = function(){
countDown(10);
}
});
Then in the html I added a button to start and stop the interval like so:
<body ng-app="app">
<div ng-controller="BaseController as baseCtrl">
{{ baseCtrl.remainingTime }}
<div>
<button ng-click="baseCtrl.startInterval()">Start Countdown</button>
<button ng-click="baseCtrl.stopInterval()">Stop Countdown</button>
</div>
</div>
</body>
You can view the codepen example here

Timer keeps getting faster on every reset

The timer keeps getting faster every time I reset it. I'm thinking I need to use clearTimeout but am unsure about how to implement it. Here's the code:
$(function(){
sessionmin = 25;
$("#sessionMinutes").html(sessionmin);
$("#circle").click(function() {
timeInSeconds = sessionmin * 60;
timeout();
});
})
function timeout(){
setTimeout(function () {
if (timeInSeconds > 0) {
timeInSeconds -= 1;
hours = Math.floor(timeInSeconds/3600);
minutes = Math.floor((timeInSeconds - hours*3600)/60);
seconds = Math.floor(timeInSeconds - hours*3600 - minutes*60);
$("#timer").html(hours + ":" + minutes + ":" + seconds);
}
timeout();
}, 1000);
}
You have to define your setTimeout as a variable to reset it.
See Fiddle
var thisTimer; // Variable declaration.
$(function(){
sessionmin = 25;
$("#sessionMinutes").html(sessionmin);
$("#circle").click(function(){
clearTimeout(thisTimer); // Clear previous timeout
timeInSeconds = sessionmin * 60;
timeout();
});
})
function timeout(){
thisTimer = setTimeout(function () { // define a timeout into a variable
if(timeInSeconds>0){
timeInSeconds-=1;
hours = Math.floor(timeInSeconds/3600);
minutes = Math.floor((timeInSeconds - hours)/60);
seconds = (timeInSeconds - hours*3600 - minutes*60)
$("#timer").html(hours + ":" + minutes + ":" + seconds);
}
timeout();
}, 1000);
}
You should: use setInterval instead of setTimeout, return the interval id that setInterval generates, clear that interval before you restart it. Here is an example: https://jsfiddle.net/8n2b7x0s/
$(function(){
var sessionmin = 25;
var intervalId = null;
$("#sessionMinutes").html(sessionmin);
$("#circle").click(function() {
timeInSeconds = sessionmin * 60;
// clear the current interval so your code isn't running multiple times
clearInterval(intervalId);
// restart the timer
intervalId = run();
});
})
function run(){
return setInterval(function () {
if(timeInSeconds>0){
timeInSeconds-=1;
hours = Math.floor(timeInSeconds/3600);
minutes = Math.floor((timeInSeconds - hours)/60);
seconds = (timeInSeconds - hours*3600 - minutes*60)
$("#timer").html(hours + ":" + minutes + ":" + seconds);
}
}, 1000);
}

Categories

Resources