How to exam wise countdown timer start [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I create online examination system and i create different exam and different time assign ,i click any exam accroding to countdown timer start,
see below screenshot
ScreenShot-1
Screenshot-2
View:
<input type="hidden" name="time_limit" id="time_limit" value="<?php echo $examination_test_result['time_limit']; ?>">
<div class="box-body">
<h2><p style="float: right" id="countdown"></p></h2>
<script>
$time_limit = $("#time_limit").val();
var d = new Date($time_limit);
var hours = d.getHours();
var minutes = d.getMinutes();
var seconds = 60 * minutes;
if (typeof (Storage) !== "undefined") { //checks if localStorage is enabled
if (localStorage.seconds) { //checks if seconds are saved to localstorage
seconds = localStorage.seconds;
}
}
function secondPassed() {
var minutes = Math.round((seconds - 30) / 60);
var hours = Math.round((minutes) / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
if (typeof (Storage) !== "undefined") {
localStorage.setItem("seconds", seconds);
}
document.getElementById('countdown').innerHTML = hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(myVar);
document.getElementById('countdown').innerHTML = alert('Timeout');
window.location.href = base_url + "student/Examinations";
if (typeof (Storage) !== "undefined") {
localStorage.removeItem("seconds");
}
} else {
seconds--;
}
}
var myVar = setInterval(secondPassed, 1000);
});
</script>
MY Question: I click different exam and examwise countdown timer start. but i have problem i click any exam and countdown timer continue

Like I said in another thread, you need to remove the countdown from the LocalStorage. To achieve this you need to perform this action on an defined event, like a button click, or whatever.
function resetCountdownInLocalStorage(){
localStorage.removeItem("seconds");
}
You can call this action, like I mentioned on for example the click event of your "Next" button, or on every Restart of the test.
For example if you want to call this action on your Next button and we assume that the button has the Id next you can achieve the requested action by using this javascript snippet:
document.getElementById("next").onclick = function() {
localStorage.removeItem("seconds");
}
Or using the function from above:
document.getElementById("next").onclick = resetCountdownInLocalStorage;

From your question i think you want a set of timers that will work independently. I have created an example. Please check this Fiddle
HTML
<div class="timer" started="false" timerObj="" value="10">
Start Timer
<div id="timer1"></div>
</div>
<br>
<div class="timer" started="false" timerObj="" value="10">
Start Timer
<div id="timer2"></div>
</div>
<br>
<div class="timer" started="false" timerObj="" value="10">
Start Timer
<div id="timer3"></div>
</div>
CSS
.timer {
border-radius: 2px;
background: #73AD21;
padding: 20px;
width: 100px;
height: 20px;
}
JS
$(document).ready(function() {
function myTimer(resultDivId) {
var currentVal = $("#"+ resultDivId).parent().attr("value");
currentVal--;
if(currentVal == 0) {
var timerObj = $("#"+ resultDivId).parent().attr('timerObj');
clearInterval(timerObj);
}
$("#"+ resultDivId).html(currentVal);
$("#"+ resultDivId).parent().attr("value",currentVal);
}
$(".timer").click(function(){
if ($(this).attr('started') == "false") {
var currentDivId = $(this).children('div').prop("id");
var timerObj = setInterval(function(){ myTimer(currentDivId) }, 1000);
$(this).attr('started','true');
$(this).attr('timerObj',timerObj);
}
else {
var timerObj = $(this).attr('timerObj');
clearInterval(timerObj);
}
});
});
The timer will start when you click on div. It will stop if you click the div second time. You can also set separate count down for each div.

Related

How do I record multiple time values, one after another

I have an issue with printing 5 different values one after another. My code is supposed to work like this:
The user presses the the start button, the timer begins, then the user presses the stop button, the timer stops and the time that has passed is printed below. The user does that 5 times and each entry below is supposed to have a different time value based on how fast the user was. (e.g. "1. you took 2.3 seconds. 2. you took 1.7 seconds. etc.).
My code seems to print the first time value, but when I couldn't get it to work with the second attempt, I've tried adding if statements to check if the first inner html label is filled, but that didn't work.
Here is my code:
var status = 0; //0:stop 1:running
var time = 0;
var f = 0;
var s = 0;
var t = 0;
var f = 0;
var f2 = 0;
function start() {
status = 1;
document.getElementById("startBtn").disabled = true;
timer();
if (f = 0) {
f + 1;
} else if (f > 0) {
s + 1;
}
}
function stop() {
if (f = 1) {
document.getElementById("first").innerHTML = time + 1;
f++;
}
if (s = 1) {
document.getElementById("second").innerHTML = time + 1;
s++;
}
status = 0;
document.getElementById("startBtn").disabled = false;
}
function reset() {
status = 0;
time = 0;
document.getElementById('timerLabel').innerHTML = '00:00:00';
document.getElementById("startBtn").disabled = false;
}
function timer() {
if (status == 1) {
setTimeout(function() {
time++;
var min = Math.floor(time / 100 / 60);
var sec = Math.floor(time / 100);
var mSec = time % 100;
if (min < 10) {
min = "0" + min;
}
if (sec >= 60) {
sec = sec % 60;
}
if (sec < 10) {
sec = "0" + sec;
}
document.getElementById('timerLabel').innerHTML = min + ":" + sec + ":" + mSec;
timer();
}, 10);
}
}
<div class="container">
<h1 class="title">Stopwatch</h1>
<h1 id="timerLabel">00:00:00</h1>
<input type="button" value="START" class="myButton" onClick="start()" id="startBtn">
<input type="button" value="STOP" class="myButton" onClick="stop()">
<input type="button" value="RESET" class="myButton" onClick="reset()">
<h2 id="first">0</h2>
<h2 id="second">0</h2>
<h2 id="third">0</h2>
<h2 id="forth">0</h2>
<h2 id="fifth">0</h2>
</div>
I see several issues right away.
First you have var f = 0 twice.
You have f + 1; and s + 1; but those statements don't return anything, you want s++; and f++; or s+=1; and f+=1; if you want the s and f variables to increment.
Your if conditions use =, which is for assignment and therefore will always return true, instead of == (equality with conversion) or better yet, === (strict equality).
Fixing those issues will probably get you up and running.
But, you've also got too much complication in this solution.
First, you should not be using inline HTML event attributes (onclick, etc.) and instead, you should be setting up all your event handling in JavaScript.
Next, it seems that you have too many variables for what you are trying to do. There really isn't a need for status as far as I can tell. If you are in the stop function, it's obvious that you are stopped. If you are in the timer function, you must be started. I also don't see the need for the f, s, f2 and t variables or the code that tracks them.
You forgot to check mSec for single digits and prepend a 0 in those cases.
Only use .innerHTML when the string you are supplying contains HTML that needs to be parsed by the browser. If there is no HTML in the string, the HTML parser will be invoked for no reason and that's a waste of resources. For non-HTML strings, use .textContent.
You also don't need to set up empty <h2> placeholders for the results ahead of time. You can create them on the fly so there will be less HTML and less JavaScript to try to test for them and match them.
Related to the <h2> comment, you should be using tags because of the semantics they convey, not because of the default formatting the browser applies to them. <h1>is fine for your page title of Stopwatch because that's a heading, but it's incorrect for showing the elapsed time because that's not a section heading. And, to show the various times between clicks, a bullet list is appropriate because you are, well, making a list. Use the right tag for the job, but then use CSS to style anything anyway that you want.
And, by separating out the code that creates the 00:00:00 string into its own function, you can call it whenever you need that format created.
I believe I've accomplished what you want below. See comments for explanations:
var time = 0; // Store the elapsed time count
var timeout = null; // Will hold a reference to the setTimeout
var lastTime = null; // Stores the time count when the stop button was last pressed
// Get all the DOM references you'll be working with, just once
// and make them available to all the functions so you don't need
// to keep finding them over and over.
var btnStart = document.getElementById("startBtn");
var btnStop = document.getElementById("stopBtn");
var btnReset = document.getElementById("resetBtn");
var timerLabel = document.getElementById('timerLabel');
var results = document.getElementById("results");
// Set up your event handlers in JavaScript, not in HTML
btnStart.addEventListener("click", start);
btnStop.addEventListener("click", stop);
btnReset.addEventListener("click", reset);
function start() {
btnStart.disabled = true;
timeout = setTimeout(function(){
time++; // Increment time count
timerLabel.textContent = getFormattedTime(time); // Update counter with formatted time
start(); // Run timer again
}, 10);
}
function stop() {
clearTimeout(timeout); // Stop the timer
var li = document.createElement("li"); // Create a new <li> element
li.textContent = getFormattedTime(time - lastTime); // Set the text for the element
lastTime = time; // Store the time that the timer stopped
results.appendChild(li); // Add the <li> to the static <ul>
btnStart.disabled = false; // Disable the start button
}
function reset(){
clearTimeout(timeout); // Stop the timer
time = 0; // Reset the time
lastTime = 0; // Reset the last time
timerLabel.textContent = '00:00:00'; // Reset the time label
btnStart.disabled = false; // Enable the start button
results.innerHTML = ""; // Clear out the static <ul>
}
// This function accepts the time count and retuns it in a 00:00:00 format
function getFormattedTime(timeVal){
var min = Math.floor(timeVal/100/60);
var sec = Math.floor(timeVal/100);
var mSec = timeVal % 100;
if(min < 10) { min = "0" + min; }
if(sec >= 60) { sec = sec % 60; }
if(sec < 10) {
if(sec === 0) {
sec = "00";
} else {
sec = "0" + sec;
}
}
if(mSec < 10) {
if(mSec === 0) {
mSec = "00";
} else {
mSec = "0" + mSec;
}
}
return min + ":" + sec + ":" + mSec;
}
/* Make elapsed time area stand out */
#timerLabel {
font-size:2em;
font-weight:bold;
margin-bottom:1em;
background-color:#ff00ff;
font-family:Arial, Helvetica, sans-serif;
display:inline-block;
padding:15px;
width:10em;
text-align:center;
}
ul { padding:0; } /* remove default indentation of list */
li { list-style-type: none; } /* remove standard bullet discs */
li::before { content: " - "; } /* place a dash before each list item instead */
<div class="container">
<h1 class="title">Stopwatch</h1>
<div id="timerLabel">00:00:00</div>
<div>
<input type="button" value="START" class="button" id="startBtn">
<input type="button" value="STOP" class="button" id="stopBtn">
<input type="button" value="RESET" class="button" id="resetBtn">
</div>
<ul id="results"></ul>
</div>

Stopwatch Not working

I found this stopwatch tutorial online, however when i tried implementing it, it kept saying "TypeError: start is null" and "TypeError: h1 is undefined" in the console when i inspect the element. What is bugging me even further is that when i insert the code in here it works and if i put it into notepad++ it does not work. Is there a jquery file that i might have missed during the implementation and some how snippet is making it work?
var h1 = document.getElementsByTagName('h1')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0, minutes = 0, hours = 0,
t;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
t = setTimeout(add, 1000);
}
timer();
/* Start button */
start.onclick = timer;
/* Stop button */
stop.onclick = function() {
clearTimeout(t);
}
/* Clear button */
clear.onclick = function() {
h1.textContent = "00:00:00";
seconds = 0; minutes = 0; hours = 0;
}
<h1><time>00:00:00</time></h1>
<button id="start" >start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
Wrap all your code, including functions, in a comon function that you could name initialize() { }.
Then, put on your <body> tag the function binded onload event like following :
<body onload="initialize()">
This will tell your code not to execute unless the whole DOM and element have been created, because you can't access your elements unless they are all fully loaded.
Likely, you have defined your Javascript BEFORE your HTML. Remember Javascript is a blocking language, so it will halt all operation (including loading the HTML) until the script is finished.
Move the script below your HTML or use some form of $(document)ready

Javascript Function activates before button is clicked

If requirements are met when you click the button it will display a count down timer. Problem is it displays the countdown timer BEFORE you even click the button. I'm not sure what I'm overlooking.
<input id="upgrade" type="button" value="Upgrade" onclick="timer();" />
<br><br><br><br>
<p id="countdown_timer"></p>
<script>
function display_timer(){
document.getElementById("countdown_timer").innerHTML = "<span id='countdown' class='timer'></span>";
}
</script>
<script>
var currently_upgrading = 0;
var current_ore = 398;
var current_crystal = 398;
var upgradeTime = 172801;
var seconds = upgradeTime;
function timer() {
if(currently_upgrading == 1){alert('You are already upgrading a module.');return;}
if(current_ore <= 299){alert('You need more ore.');return;}
if(current_crystal <= 299){alert('You need more crystal.');return;}
display_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 = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
</script>
You need to move countdownTimer variable into your timer() function.
Try changing the last lines of timer() to be like this:
if (seconds == 0) {
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
setTimeout(timer, 1000);
}
and remove the setInterval line.
Speaking generally, setTimeout is much preferred to setInterval, because it doesn't require a managed state (countdownTimer in your example) and is far more flexible.
Also note that passing a string as in setTimeout('timer()', 1000) is obsolete, just pass a function: setTimeout(timer, ...).
This line
var countdownTimer = setInterval('timer()', 1000);
will execute 1 second after the page loads as well as on the button click and this calls the display_timer function.
you have called it in setInterval function, so it will starts immediately , because setInterval function runs after page loads and not on click and setInterval uses your function

Pause / Resume jQuery Countdown Timer

I'm trying to make a countdown timer that can be paused with a single HTML5 button tag using a JS onClick() event, or more preferably, using jQuery with something like $("#pause_resume").off('click').on('click', firstClick)in conjunction with another function. Logically, I would assume the task would require getting the current values of both $.min and $.sec and then setting these values, while switching functions, until the "resume" button is pressed again. But I honestly have no idea how to go about doing this. I've looked at other code on this site and others, but what I saw was heavily deprecated and not in line with my project plan. Any insight is appreciated.
HTML:
<p class="timer">
<span class="min"></span>:<span class="sec"></span>/
<span class="fullTime">1:30</span>
</p>
JavaScript:
<script type="text/javascript">
var timer = $('.timer');
var leadingZero = function(n) {
if (n < 10 && n >= 0)
return '0' + n;
else
return n;
};
var minutes = 1;
var seconds = 30;
setInterval(function () {
var m = $('.min', timer),
s = $('.sec', timer);
if (seconds == 0) {
minutes--;
seconds = 59;
} else {
seconds--;
}
m.text(minutes);
s.text(leadingZero(seconds));
}, 1000);
</script>
Well, I think this is what you want. http://jsfiddle.net/joey6978/67sR2/3/
I added a button that toggles a boolean on click to determine whether to set your function in the interval or to clear the interval.
var clicked=true;
var counter;
$('button').click(function(){
if(clicked){
counter=setInterval(function () {
var m = $('.min', timer),
s = $('.sec', timer);
if (seconds === 0) {
minutes--;
seconds = 59;
} else {
seconds--;
}
m.text(minutes);
s.text(leadingZero(seconds));
}, 1000);
}
else{
clearInterval(counter);
}
clicked=!clicked;
});

How to set one minute counter in javascript?

In my project ,I have list of questions, for every question have three option answers.
After see the question if i want answer that question means click "show answer" button .
when I click button ,counter starts for one minute after one minute error will show .
can any one help ?
You could use something like this:
function gameLost() {
alert("You lose!");
}
setTimeout(gameLost, 60000);
UPDATE: pass function reference to setTimeout() instead of code string (did I really write it that way? O_o)
EDIT
To display the timer too (improved version, thanks to davin too):
<button onclick="onTimer()">Clickme</button>
<div id="mycounter"></div>
<script>
i = 60;
function onTimer() {
document.getElementById('mycounter').innerHTML = i;
i--;
if (i < 0) {
alert('You lose!');
}
else {
setTimeout(onTimer, 1000);
}
}
</script>
......
function timedOut() {
alert("Some error message");
}
// set a timer
setTimeout( timedOut , 60000 );
That basically sets a timer that will execute the given function after 60.000 miliseconds = 60 seconds = 1 minute
Edit: here's a quick, imperfect fiddle that also shows the countdown http://jsfiddle.net/HRrYG
function countdown() {
var seconds = 60;
function tick() {
var counter = document.getElementById("counter");
seconds--;
counter.innerHTML = "0:" + (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
alert("Game over");
}
}
tick();
}
// start the countdown
countdown();
You will want to use the setTimout function check out this article. https://developer.mozilla.org/En/Window.setTimeout Remember the timer is in milliseconds so for one minute is 60,000.
// this is the simplest way to one mint counter .this is also use in angular and oops
var i=60;
function coundown(){
setInterval(() => {
if (this.i == 0) {
return;
}
console.log(this.i--);
}, 1000);
}
// this function you can call when otp is comming or form submit and waiting for otp countdown
angular #javascript #typescript
you can try to use this
or visit for more details Demo
Demo2
function countdown() {
var seconds = 59;
function tick() {
var counter = document.getElementById("counter");
seconds--;
counter.innerHTML =
"0:" + (seconds < 10 ? "0" : "") + String(seconds);
if (seconds > 0) {
setTimeout(tick, 1000);
} else {
document.getElementById("verifiBtn").innerHTML = `
<div class="Btn" id="ResendBtn">
<button type="submit">Resend</button>
</div>
`;
document.getElementById("counter").innerHTML = "";
}
}
tick();
}
countdown();
<div class="btnGroup">
<span class="Btn" id="verifiBtn">
<button type="submit">Verify</button>
</span>
<span class="timer">
<span id="counter"></span>
</span>
</div>

Categories