Timer em JAVASCRIPT [closed] - javascript

Closed. This question is not written in English. It is not currently accepting answers.
Stack Overflow is an English-only site. The author must be able to communicate in English to understand and engage with any comments and/or answers their question receives. Don't translate this post for the author; machine translations can be inaccurate, and even human translations can alter the intended meaning of the post.
Closed yesterday.
Improve this question
Estou implementando um timer em que existe um botão de start e um de pausa. Consigo pausar ao clicar no botão porém quando clico em start ele reinicia, não voltando de onde foi pausado. Se crio uma variável que contém o timeLeft o código fica lendo e o setInterval() atualiza a cada dois segundos apenas.
const queryString = window.location.search;
const params = new URLSearchParams(queryString);
const sessionTimeInMinutes = params.get("option");
const retireTimeInMinutes = params.getAll("option")[1];
var sessionSelected = document.getElementById("select-session-btn");
var retireSelected = document.getElementById("select-retire-btn");
var sessionInterval, retireInterval, remainingTimeSession, remainingTimeRetire, timer;
function startSessionTimer(duration, display) {
var timer = duration;
var minutes, seconds;
sessionInterval = 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 = duration;
}
}, 1000);
}
function startRetireTimer(duration, display) {
var timer = duration;
var minutes, seconds;
retireInterval = 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 = duration;
}
}, 1000);
}
function restartTimer(){
if (sessionSelected.classList[1] == 'active') {
clearInterval(sessionInterval);
startSessionTimer(sessionTimeInMinutes * 60, sessionTimerShowing);
}
else if (retireSelected.classList[1] == 'active') {
clearInterval(retireInterval);
startRetireTimer(retireTimeInMinutes * 60, retireTimerShowing);
}
}
var sessionTimerShowing = document.getElementById("timer-showing-session");
sessionTimerShowing.textContent = sessionTimeInMinutes + ":00"
var retireTimerShowing = document.getElementById("timer-showing-retire");
retireTimerShowing.textContent = retireTimeInMinutes + ":00"
const startBtn = document.getElementById("start-btn");
const restartBtn = document.getElementById("restart-btn");
const stopBtn = document.getElementById("stop-btn");
startBtn.addEventListener("click", function(){
if (sessionSelected.classList[1] == 'active') {
var sessionDuration = remainingTimeSession > 0 ? remainingTimeSession : sessionTimeInMinutes * 60;
startSessionTimer(sessionDuration, sessionTimerShowing);
}
else if (retireSelected.classList[1] == 'active') {
var retireDuration = remainingTimeRetire > 0 ? remainingTimeRetire : retireTimeInMinutes * 60;
startRetireTimer(retireDuration, retireTimerShowing);
}
})
restartBtn.addEventListener("click", function() {
if (sessionSelected.classList[1] == 'active') {
clearInterval(sessionInterval);
startSessionTimer(sessionTimeInMinutes * 60, sessionTimerShowing);
}
else if (retireSelected.classList[1] == 'active') {
clearInterval(retireInterval);
startRetireTimer(retireTimeInMinutes * 60, retireTimerShowing);
}
})
stopBtn.addEventListener("click", function() {
if (sessionSelected.classList[1] == 'active') {
clearInterval(sessionInterval);
}
else if (retireSelected.classList[1] == 'active') {
clearInterval(retireInterval);
}
})

Related

How to reset Time Countdown with logout?

I have created online quiz with MVC5 each question in single page the time countdown start when student start his exam from question one to end of exam.
this is the script:
<script type="text/javascript">
javascript: window.history.forward(1);
</script>
<script>
var timeoutHandle;
function countdown(minutes, stat) {
var seconds = 60;
var mins = minutes;
if (getCookie("minutes") && getCookie("seconds") && stat) {
var seconds = getCookie("seconds");
var mins = getCookie("minutes");
}
function tick() {
var counter = document.getElementById("timer");
setCookie("minutes", mins, 10)
setCookie("seconds", seconds, 10)
var current_minutes = mins - 1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
//save the time in cookie
if (seconds > 0) {
timeoutHandle = setTimeout(tick, 1000);
} else {
if (mins > 1) {
setTimeout(function () { countdown(parseInt(mins) - 1, false); }, 1000);
} else {
window.location.replace("/StudentControl/LogOut");
return false;
}
}
}
tick();
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
window.location.replace("/StudentControl/LogOut");
}
}
return "";
}
window.onload = function startingTimer() {
//countdown(prompt("Enter how many minutes you want to count down:"),true);
var reqt = $("#reqtimer").val();
countdown(reqt, true);
}
</script>
every thing is working fine the problem is:
if the student end early and logout and other student use his computer ,login and start his exam the time will continue from the last time for the pervious student.
Is there any way to reset the browser history or reset the countdown with logout command?

After button click timer should start again

<script>
var minutes = 1;
var seconds = 45;
$(document).ready(function () {
setInterval(startTimer, 1000);
});
function startTimer() {
document.getElementById("timer").innerHTML = (minutes - 1) + ":" + --seconds;
if (seconds == 0) {
minutes--;
if (minutes != 0) {
seconds = 60;
} else {
seconds = 0;
}
}
if (minutes == 0 && seconds == 0) {
document.getElementById('next').click();
minutes = 1;
seconds = 45;
}
}
</script>
This is my code for the timer and it should restart after button click whose id is #next. I did many things but it won't work. Please help.
Button Id = Next
Here's my solution to your issue.
I've noticed $(document).ready() so I instantly presumed you are
using jQuery.
var timerInterval is a direct reference to the timer that you started.
To stop the timer, use clearInterval(timerInterval) [Same story goes for setTimeout()].
I've changed your countdown timer because I couldn't be bothered fixing it.
var timerInterval;
let minutes = 2;
let seconds = 42;
let duration = (minutes * 60) + seconds;
let display = document.querySelector('#timer');
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
timerInterval = 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 = duration;
clearInterval(timerInterval);
}
}, 1000);
}
startTimer(duration, display);
$('button').click((e) => {
clearInterval(timerInterval);
startTimer(duration, display);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="timer"></span>
<br>
<button>Reset Timer</button>
You should not rely on setInterval (or setTimeout) to calculate a time value. It is not guaranted to be called at the specified interval. I believe in some case it could also be paused by the browser.
You could try something like this :
<span id='timer'></span>
<button id='next'>Next</button>
<script>
var btn = document.getElementById('next');
btn.addEventListener('click', function(e) {
// 10 is the duration in seconds
startNextTimer(10, function() { alert('done!');} );
});
function startNextTimer(numSecondsDuration, callback) {
var label = document.getElementById('timer');
var endDate = new Date();
endDate.setSeconds(endDate.getSeconds() + numSecondsDuration);
var calcTimeLeft = function() { return Math.ceil((endDate - (new Date())) / 1000); };
label.innerHTML = calcTimeLeft() + " secs";
var intervalId = setInterval(function() {
var numSecondsLeft = calcTimeLeft();
if (numSecondsLeft <= 0) {
clearInterval(intervalId);
if (callback) {
callback();
}
}
label.innerHTML = numSecondsLeft + " secs";
}, 500);
}
</script>
Without the html I can't give you step by step but basically, you need to clear the interval before you can restart it.
<script>
var minutes = 1;
var seconds = 45;
var interval_id=setInterval(startTimer, 1000);
$('#next').on("click",function(){
clearInterval(interval_id);
minutes = 1;
seconds = 45;
document.getElementById("timer").innerHTML ="";
interval_id=setInterval(startTimer, 1000);
});
function startTimer() {
document.getElementById("timer").innerHTML = (minutes - 1) + ":" + --seconds;
if (seconds == 0) {
minutes--;
if (minutes != 0) {
seconds = 60;
} else {
seconds = 0;
}
}
if (minutes == 0 && seconds == 0) {
minutes = 1;
seconds = 45;
}
}
</script>

Countdown Timer to Add extra 2 minutes

I have created a countdown timer and am trying to add 2 minutes into the existing timer to extend the timer.
My Code
function CountDownTimer(duration, granularity) {
this.duration = duration;
this.granularity = granularity || 1000;
this.tickFtns = [];
this.running = false;
}
CountDownTimer.prototype.start = function() {
if (this.running) {
return;
}
this.running = true;
var start = Date.now(),
that = this,
diff, obj;
(function timer() {
diff = that.duration - (((Date.now() - start) / 1000) | 0);
if (diff > 0) {
setTimeout(timer, that.granularity);
} else {
diff = 0;
that.running = false;
}
obj = CountDownTimer.parse(diff);
that.tickFtns.forEach(function(ftn) {
ftn.call(this, obj.minutes, obj.seconds);
}, that);
}());
};
CountDownTimer.prototype.onTick = function(ftn) {
if (typeof ftn === 'function') {
this.tickFtns.push(ftn);
}
return this;
};
CountDownTimer.prototype.expired = function() {
return !this.running;
};
CountDownTimer.parse = function(seconds) {
return {
'minutes': (seconds / 60) | 0,
'seconds': (seconds % 60) | 0
};
};
$(document).ready(function() {
var counter = 0;
var display = document.querySelector('#time'),
//timer = new CountDownTimer(600);
timer = new CountDownTimer(125); // for debug
timer.onTick(format).onTick(restart).start();
function restart() {
if (this.expired()) {
alert("Expired");
}
}
function format(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ':' + seconds;
if (minutes < 2) {
if (counter == 0) {
alert("Extending Time");
counter++;
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="time"></span> minutes
I managed to trigger an event that after 2 minutes will show an alert that the time will be extended, but so far, I can't think of any method or functions I can use to add the extra time. Is there any way I can do this?
Add code as following:
CountDownTimer.prototype.reset = function (duration) {
this.duration = duration;
}
and rewrite function format as :
function format(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ':' + seconds;
if (minutes < 2) {
if (counter == 0) {
//alert("Extending Time");
timer.reset(timer.duration + 120);
counter++;
}
}
}
You can add code in CountDownTimer.prototype.start before setTimeout like:
this.instance = setTimeout(...)
add function:
CountDownTimer.prototype.kill = function() {
clearTimeout(this.instance)
}
call function kill to stop timer permanently.

timer gets autorefreshed on refreshing page

Here i am facing one problem i am preparing quiz application in php
i face one problem when users starts the test the timer is running properly. when user go for second question the timer starts again
here is my code:-
window.onload = start();
var mins = 10;
var secs = 0;
var timer;
function start() {
timer = setInterval(
function() {
update();
}, 1000);
}
function update() {
var timeField = document.getElementById('time');
if (secs == 0) {
if (mins == 0) {
timeField.innerHTML = 'Times up!';
clearInterval(timer);
alert('Times up');
return;
}
mins--;
secs = 59;
} else {
secs--;
}
if (secs < 10) {
timeField.innerHTML = 'Time left: ' + mins + ':0' + secs;
} else {
timeField.innerHTML = 'Time left: ' + mins + ':' + secs;
}
}
<div id="time" > </div>
you need to store the time on cookies or localStorage, or using server time. here is the code using localStorage
window.onload = start();
var timer;
function start() {
var mins = 10;
var secs = 0;
var end = parseInt(localStorage.getItem('end'));
var time;
if (! isNaN(end)) {
time = Math.floor((end - Date.now()) / 1000);
} else {
time = mins * 60 + secs
localStorage.setItem('end', (Date.now() + (time * 1000)));
}
timer = setInterval(update(time), 1000);
}
function update(time) {
return function() {
var timeField = document.getElementById('time');
if (time <= 0) {
timeField.innerHTML = 'Times up!';
clearInterval(timer);
alert('Times up');
return;
} else {
time--;
}
var mins = Math.floor(time / 60);
var secs = time % 60;
if (secs < 10) {
timeField.innerHTML = 'Time left: ' + mins + ':0' + secs;
} else {
timeField.innerHTML = 'Time left: ' + mins + ':' + secs;
}
}
}
<div id="time" > </div>

How to fix javascript countdown seconds bug

so I have this countdown timer I created,
<script type="text/javascript">
var interval;
var minutes = 12;
var seconds = 32;
window.onload = function() {
countdown('countdown');
}
function countdown(element) {
interval = setInterval(function() {
var el = document.getElementById(element);
if(seconds == 0) {
if(minutes == 0) {
minutes=7;
seconds=47;
} else {
minutes--;
seconds = 60;
}
}
if(minutes > 0) {
var minute_text = minutes + (minutes > 1 ? ':' : ':');
} else {
var minute_text = '';
}
var second_text = seconds > 1 ?'':'';
el.innerHTML = minute_text + ''+seconds + ' '+second_text + ' remaining';
seconds--;
}, 1000);
}
</script>
The result works perfectly, but when the timer reaches digits below 10, (12:03, 12:05, etc.) it displays the seconds without a '0' in the front. (12:3 instead of 12:03)
I tried fixing this, but it has brought me nowhere. Is it possible to somehow edit my script to fix this bug?
second_text = (seconds > 9) ? (seconds) : ('0' + seconds);
I just cleaned your code a bit:
var interval,
minutes = 12,
seconds = 32;
window.onload = function() {
countdown('countdown');
}
function countdown(element) {
var el = document.getElementById(element),
minutes_text, second_text;
interval = setInterval(function() {
if(seconds == 0) {
if(minutes == 0) {
minutes=7;
seconds=47;
}
else {
minutes--;
seconds = 60;
}
}
minutes_text = minutes;
second_text = (seconds < 10 ? "0" : "") + seconds;
el.innerHTML = minutes_text + ':' + second_text + ' remaining';
seconds--;
}, 1000);
}
A number does not have a zero in front of it.
You have to manually add that.
if(seconds < 10) {
second_text = "0" + seconds;
}
try adding a function to pad the value displayed
function padvalue(i) {
if (i<10) {
i="0" + String(i);
}
return i;
}
Call it here
el.innerHTML = minute_text + '' + padvalue(seconds) + ' ' + second_text + ' remaining';
Use this snippet to convert the numbers to strings:
var secondStr = seconds + "";
while (secondStr.length < 2) {
secondStr = "0" + secondStr;
}
Do the same thing for minutes and hours and then print the strings.
(You do know that doing an interval of 1000 means the interval will be 1000 or more milliseconds? It's unlikely that you miss a whole tick though with that long of an interval. This means the counter will be close to real time seconds but not exact and will vary from time to time and computer to computer.)

Categories

Resources