Add a timer to online quiz that submits the quiz - javascript

I am developing a web based system wherein user can give tests submitted by admin, the issue is i want to implement a timer that can initiate at start of the quiz and autosubmit the test as soon as it ends , need help on how do i implement read a lot of aanswers but did not help specific to my project .`
<span id="countdown" class="timer"></span>
<script>
var seconds = 40;
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Buzz Buzz";
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
</script>
`

Related

Countdown It does not Work with click button

I have a simple question. I want to make this code work with the Reset time button when the time is start again from 30 min delete the ( You are Ready! ) and start the time
var seconds = 30;
function secondPassed() {
var minutes = Math.round((seconds - 30) / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "You are Ready!";
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
<span id="countdown" class="timer">
Reset time
I created a new function to reset the seconds and restart the timer and linked it to the button. I have also isolated at the start of the js code the variables that will count the seconds and hold the reference to the Interval.
is this what you are looking for?
var seconds;
var countdownTimer;
function startTimer() {
if (!seconds || seconds == 0) {
seconds = 30;
clearInterval(countdownTimer);
countdownTimer = setInterval(secondPassed, 1000)
secondPassed();
}
}
function secondPassed() {
var minutes = Math.round((seconds - 30) / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "You are Ready!";
} else {
seconds--;
}
}
startTimer();
<html>
<body>
<div>
<span id="countdown" class="timer"></span>
</div>
Reset time
</body>
</html>
Here create a separate function where after clicking - it disables the button, sets the timer, and changes button text.
In secondPassed method, if seconds == 0, it enables the button, so that you can start count down again.
var seconds = 30;
var countdownTimer;
function secondPassed() {
var minutes = Math.round((seconds - 30) / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0)
{
clearInterval(countdownTimer);
document.getElementById('reset').disabled = false;
document.getElementById('countdown').innerHTML = "You are Ready!";
} else
{
seconds--;
}
}
function start(){
seconds = 30;
document.getElementById('reset').innerHTML = "Reset";
document.getElementById('reset').disabled = true;
countdownTimer = setInterval('secondPassed()', 1000);
}
//on load call
start();
<div>
<span id="countdown" class="timer"/>
</div>
<button id="reset" onclick="start()">
Start
</button>
Let's assume something quite basic, like the following:
<div>00:00</div>
<button>Reset</button>
Below is an approach you could take, fully-commented.
// We'll start by getting a couple element references
const label = document.querySelector("div");
const button = document.querySelector("button");
// Next, we'll bind-up the click handler for the button
button.addEventListener("click", () => {
// When the user clicks the button, we'll set the time
// limit to 30 minutes and proceed
let timer = 60 * 30;
// Disable the button to prevent further clicks
button.disabled = true;
button.dataset.default = button.textContent;
button.textContent = "Now counting down!";
// Let's setup some code that will be executed every second
button.interval = setInterval(() => {
// This decimal will be a number like 29.9521
const decimal = timer / 60;
// We'll convert 29.9521 into 29, for 29 minutes
const wholeMinute = Math.floor(decimal);
// Next, we'll take the .9521 and multiply by 60 for seconds
const wholeSecond = Math.round(60 * (decimal - wholeMinute));
// We'll pad both of the numbers so they always have a leading 0
const lblMin = wholeMinute.toString().padStart(2, 0);
const lblSec = wholeSecond.toString().padStart(2, 0);
// As long as we aren't out of seconds
if (timer >= 0) {
// Reduce the timer by 1 second
timer = timer - 1;
// And print the new label on our label element
label.textContent = `${ lblMin }:${ lblSec }`;
// Then return, so we don't execute what comes next
return;
}
// If we made it this far, our timer ran out
// Start by enabling the button
button.disabled = false;
// Restore the original text of the button
button.textContent = button.dataset.default;
// And clear our interval, as it is no longer needed
clearInterval(button.interval);
// Our interval will 'tick' once every second (1000 milliseconds)
}, 1000);
});

Js code always runs even i don't hit the button

I have a js code and I wanna run it when I click the button.It's seems ok to me but it's run even i don't hit the button.
Probably it has a simple answer but I couldn't handle it.I'm new....
var upgradeTime = 600;
var seconds = upgradeTime;
function timer() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML =
days + ":" + hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Tamamlandı.";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
<span id="countdown" class="timer"></span>
<input id="" type="button" value="clickme" onclick="timer();" />
You need to remove var countdownTimer = setInterval('timer()', 1000);
outside the function:
You can include all your core logic to a new function coreTimer()
Call coreTimer() from timer()
make sure countdownTimer is declared in global scope so that it can be cleared using clearInterval inside coreTimer() function.
var upgradeTime = 10;
var seconds = upgradeTime;
var countdownTimer;
function timer() {
countdownTimer = setInterval('coreTimer()', 1000);
}
function coreTimer() {
var days = Math.floor(seconds / 24 / 60 / 60);
var hoursLeft = Math.floor((seconds) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = days + ":" + hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Tamamlandı.";
} else {
seconds--;
}
}
<span id="countdown" class="timer"></span>
<input id="" type="button" value="clickme" onclick="timer();" />
setInterval method calls a function or evaluates an expression at specified intervals. So the statement
var countdownTimer = setInterval('timer()', 1000);
will execute your timer function every 1000 milliseconds. Hence your function is getting called even when you are not clicking the button. You need to modify that statement accordingly or remove it completely.

VueJS with normal JavaScript

I want to add count down timer to my vue component. I have found a script which is written in normal JavaScript.
this is my JavaScript file.
var upgradeTime = 7200;
var seconds = upgradeTime;
function timer() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
I stored this as a clock.js in my vue js projects src folder.
How do I import this clock.js file to my vue component and get the output.
for this JavaScript code normal way to get output would be something like this
<span id="countdown" class="timer"></span>
But how do I get an output inside a vue component.
I'm junior developer and I haven't clear idea about how to use normal JavaScript inside vue. I hope you understand my question.
Thank you
If you really want a simple and straightforward solution, you can simply put all of that within the mounted callback: that is when the component template has been parsed and the DOM constructed, so #countdown should be accessible by then. Read more about lifecycle hooks in VueJS.
Note: However, if you want to really learn how to use VueJS properly, please continue reading on how to create a custom timer component at the end of this answer :) by stuffing everything into the mounted callback, you are missing out the fun part of authoring your first and rather simple VueJS component.
Before we get started, note that there is a mistake when you invoke timer() in your setInterval callback. It should be:
var countdownTimer = setInterval(timer, 1000);
Here is a proof-of-concept example, where you "turkey stuff" all your timer logic into the mounted() callback:
new Vue({
el: '#app',
template: '#custom-component',
mounted: function() {
var upgradeTime = 7200;
var seconds = upgradeTime;
function timer() {
var days = Math.floor(seconds / 24 / 60 / 60);
var hoursLeft = Math.floor((seconds) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval(timer, 1000);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app"></div>
<script type="text/x-template" id="custom-component">
<div>
<p>I am a custom component.</p>
<p>
My timer:<br />
<span id="countdown" class="timer"></span>
</p>
</div>
</script>
A real ideal solution is to actually create a custom VueJS component for your countdown timer ;) you can do this by simply creating yet another custom component for your timer itself. Some tips and tricks:
Use props so that you can pass in a custom time period
Remember to use data to make a copy of the time period, since you are decrementing the timer, but you cannot mutate props
Use this.$el to refer to your timer component, then you can even make do without the id reference ;)
See proof-of-concept below:
Vue.component('my-timer', {
template: '#my-timer',
props: {
upgradeTime: Number
},
data: function () {
return { seconds: this.upgradeTime }
},
methods: {
timer: function() {
var days = Math.floor(this.seconds / 24 / 60 / 60);
var hoursLeft = Math.floor((this.seconds) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = this.seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
this.$el.innerHTML = hours + ":" + minutes + ":" + remainingSeconds;
if (this.seconds == 0) {
clearInterval(countdownTimer);
this.$el.innerHTML = "Completed";
} else {
this.seconds--;
}
}
},
mounted: function() {
setInterval(this.timer, 1000);
},
});
new Vue({
el: '#app',
template: '#custom-component'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app"></div>
<script type="text/x-template" id="custom-component">
<div>
<p>I am a custom component.</p>
<p>
My timer:<br />
<my-timer upgrade-time="7200"></my-timer>
</p>
</div>
</script>
<script type="text/x-template" id="my-timer">
<span class="timer"></span>
</script>
Better just make a CountdownTimer component out of that code.
Maybe have a look at this post: countdown-timer-using-vuejs

live downcounter with javascript or jquery

counter that i can change time to remain if i want from db
i have a time stamp in table in db that maybe change
now i want for example every 30sec check that and if changed my down-counter changing
my js script is:
<script>
var seconds = 100;
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = '0' + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ':' + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = 'Times Up!';
document.getElementById('passage_text').disabled = true;
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
</script>
Try changing this:
var countdownTimer = setInterval('secondPassed()', 1000);
to this:
var countdownTimer = setInterval(secondPassed, 1000);
What isn't working in your case, exactly?
BTW: Try caching reference on frequently used DOM element. See this alternative using much simpler code for formatting your time.
var display = document.getElementById('countdown');
var seconds = 100, timer;
function secondPassed() {
if ( --seconds == 0 ) {
window.clearInterval( timer );
// your code here executing when count down has finished ...
} else {
display.innerHTML = Math.floor( seconds / 60 ) + ':' + String( "0" + ( seconds % 60 ) ).substr( -2 );
}
}
timer = window.setInterval( secondPassed, 1000 );

timer speeds up on second round onwards

I have borrowed some JS code to help me create a timer for 65 seconds. My JS knowledge is basic but I managed to modify the script to work the way I want it to. However when I click on the play button the timer speeds up from the second round onwards.
HTML:
<div id="rightCol">
<span id="countdown" class="timer">Timer About to Start! </span>
<div>
<input type="button" value="Play" id="play">
</div>
</div>
JS:
var seconds = 65;
function secondPassed() {
    var minutes = Math.round((seconds - 30)/60);
    var remainingSeconds = seconds % 60;
    if (remainingSeconds < 10) {
        remainingSeconds = "0" + remainingSeconds; 
    }
    document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
    if (seconds == 0) {
        clearInterval(countdownTimer);
        document.getElementById('countdown').innerHTML = "Time's Up!";
document.getElementById("passage_text").disabled = true;
    } else {
        seconds--;
    }
}
 
var countdownTimer = setInterval('secondPassed()', 1000);
$("#play").click(function(){
seconds = 65;
var countdownTimer = setInterval('secondPassed()', 1000);
$('#passage_text').attr('disabled', false).focus();
$("#passage_text").val('');
});
I read some of the other answers similar to mine Count down timer speeds up but I don't fully understand how the secondPassed() function works to fix it.
You need to clear interval on play functionality too and make countdownTimer global. Also it's better to pass function handler to setInterval instead of string as this will work as eval function and not recommended
var seconds = 65;
var countdownTimer = null; // make it global
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Time's Up!";
document.getElementById("passage_text").disabled = true;
} else {
seconds--;
}
}
countdownTimer = setInterval(secondPassed, 1000); // removed var and passing handler instead of string.
$("#play").click(function(){
seconds = 65;
clearInterval(countdownTimer); // clear interval
countdownTimer = setInterval(secondPassed, 1000); // removed var to use global countdownTimer variable
$('#passage_text').attr('disabled', false).focus();
$("#passage_text").val('');
});
See my JS comments above

Categories

Resources