JavaScript timer for a quiz - javascript

I am making a quiz game for a project in HTML and JavaScript. On every question, the player has 15 seconds to answer. I managed to do it like this:
<body onload="setTimeout(Timer,15000)">
and then in Js:
function Timer()
{
alert("You are out of time!");
}
However, I want to be able to display how much time the player has left in a <p> tag. How could I do that?

<div id="count">Start</div>
var count = 15;
var interval = setInterval(function(){
document.getElementById('count').innerHTML=count;
count--;
if (count === 0){
clearInterval(interval);
document.getElementById('count').innerHTML='Done';
// or...
alert("You're out of time!");
}
}, 1000);

Here's a basic example of a countdown timer
var count = 15;
var timer = setInterval(function() {
console.log(count);
count--;
if(count === 0) {
stopInterval()
}
}, 1000);
var stopInterval = function() {
console.log('time is up!');
clearInterval(timer);
}
Repl: https://repl.it/I2C6

Initialize the variable 'sec' with timeout time in seconds.
Call setInterval() which has 2 parameters, 1st is the method name and 2nd parameter is interval between invoking the method mentioned in 1st parameter.
var sec = 15;
var time = setInterval(myTimer, 1000);
function myTimer() {
document.getElementById('timer').innerHTML = sec + "sec left";
sec--;
if (sec == -1) {
clearInterval(time);
alert("Time out!! :(");
}
}
Time : <span id="timer"></span>

Related

interval starting two times

When the user clicks a button an interval will start counting but the problem is that if the user clicks the button two times there will be two intervals I tried clearInterval(interval);
before assigning the interval but the timer stopped counting.
function times(){
var element=document.getElementById("sec");
counter=0;
let interval= setInterval(myFunction, 1000);
function myFunction(){
counter++;
element.innerHTML=counter;
}
}
document.querySelector('#sec').addEventListener('click', function() {
times();
})
let interval;
let counter = 0;
function times() {
clearInterval(interval);
interval = setInterval(myFunction, 1000);
counter = 0;
}
function myFunction() {
var element = document.getElementById("sec");
counter++;
element.innerHTML = counter;
console.log(counter);
}
<button id="sec">timer</button>
if to want to clear the previously set interval when ever the user clicks, Just store the interval ID in a higher scope and clear the interval the previously set interval before creating a new one.
let interval
function times(){
clearInterval(interval);
var element=document.getElementById("sec");
counter=0;
interval = setInterval(myFunction, 1000);
function myFunction(){
counter++;
element.innerHTML=counter;
}
}
You may try the following. Depending on the existence of the interval it is decided whether to (re-)start the timer or stop it.
let interval
function times(){
var element=document.getElementById("sec");
counter=0;
if (interval) {
clearInterval(interval)
interval = null
} else {
function myFunction(){
counter++;
element.innerHTML=counter;
}
element.innerHTML=counter; // just to show '0' when re-starting
interval= setInterval(myFunction, 1000);
}
}
<button onclick="times()">Start / Stop</button>
<span id="sec">0</span>

How to handle timer button to not to display negative values on click?

I have a button.
After clicking on it , 10 seconds timer starts on button with changing text.
When i click in between the timer it decrements the value by one.
And at the last shows negative value.
Also when timer becomes zero and i click button it becomes-1 , -2
It should not go below zero.
Tried by many ways but couldn't solve the issue
Here is my code
timeLeft = 10;
function countdown() {
timeLeft--;
$("#tmp_button-72286").text("Download will be ready in "+String(timeLeft)+"seconds");
if (timeLeft > 0) {
setTimeout(countdown, 1000);}
};
function timer(){
$("#tmp_button-72286").text("");
$("#tmp_button-72286").append('<a id="myLink" target="_blank" href="link"><button id="thor">Download Now</button></a>');
}
$("#tmp_button-72286").bind("click", (function () {
countdown();
var timer_var = setInterval(timer, 10 * 1000);
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button id="tmp_button-72286">Download Now</button>
With your script, the user can trigger the countdown every time they click the button. However, the user should just initiate the countdown, and the countdown should then be triggered by itself in 1 second intervals.
To achieve that, you can use a flag to check whether the timer has been initiated or not and trigger the countdown on user click only the first time:
let timeLeft = 10;
function countdown() {
if (timeLeft > 0) {
$("#tmp_button-72286").text("Download will be ready in "+String(timeLeft)+"seconds");
setTimeout(countdown, 1000);
} else {
$("#tmp_button-72286").text("");
$("#tmp_button-72286").append('<a id="myLink" target="_blank" href="link"><button id="thor">Download Now</button></a>');
}
timeLeft--;
};
let timerRunning = false;
$("#tmp_button-72286").bind("click", (function () {
if (!timerRunning) {
timerRunning = true;
countdown();
}
}));
*I also took the liberty to change the trigger of the final message to be when the timeLeft reaches 0 instead of using 2 independent timers, but you can still use your way like this:
let timeLeft = 10;
function countdown() {
timeLeft--
$("#tmp_button-72286").text("Download will be ready in "+String(timeLeft)+"seconds");
if (timeLeft > 0) setTimeout(countdown, 1000);
};
function timer() {
$("#tmp_button-72286").text("");
$("#tmp_button-72286").append(
'<a id="myLink" target="_blank" href="link"><button id="thor">Download Now</button></a>',
);
}
let timerRunning = false;
$("#tmp_button-72286").bind("click", (function () {
if (!timerRunning) {
timerRunning = true;
countdown();
let timer_var = setInterval(timer, 10 * 1000);
}
}));
Try it. I just added variable done to check when function start and prevent from restart function.
let timeLeft = 10;
let done = false;
function countdown() {
timeLeft--;
$("#tmp_button-72286").text(
"Download will be ready in " + String(timeLeft) + "seconds",
);
if (timeLeft > 0) {
setTimeout(countdown, 1000);
}
}
function timer() {
$("#tmp_button-72286").text("");
$("#tmp_button-72286").append(
'<a id="myLink" target="_blank" href="link"><button id="thor">Download Now</button></a>',
);
}
$("#tmp_button-72286").bind("click", function () {
if (!done) {
done = true;
countdown();
var timer_var = setInterval(timer, 10 * 1000);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button id="tmp_button-72286">Download Now</button>
the code can be simplified like this, no need extra variable.
timeLeft = 10;
var tmpButton = $("#tmp_button-72286")
function countdown() {
tmpButton.text("Download will be ready in " + String(timeLeft) + " seconds");
if (timeLeft-- > 0)
setTimeout(countdown, 1000);
else
tmpButton.prop('outerHTML', '<a id="myLink" target="_blank" href="link"><button id="thor">Download Now</button></a>');
};
tmpButton.on("click", countdown);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button id="tmp_button-72286">Download Now</button>

Using Onclick to call a nested function

I want to implement a basic timer program that starts a 15 second timer on start button and stops on stop button
Here is what I have done so far
JS
var timeleft = 15;
function timer(){
var downloadTimer = setInterval(function(){
if(timeleft <= 0){
clearInterval(downloadTimer);
document.getElementById("countdown").innerHTML = "Finished";
} else {
document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
}
timeleft -= 1;
}, 1000);
function timerstop(){
clearInterval(downloadTimer);
}
}
HTML
<div id="countdown"></div>
<button onclick="timer();">start</button>
<button onclick="timerstop();">stop</button>
The reason I had to use the nested function approach was to access the variable downloadtimer, the start button works as expected but on clicking the stop button I get the following error
Uncaught ReferenceError: timerstop is not defined
I would like to know if is this is a programming error or should I change my approach
Thanks in Advance
Move downloadTimer outside.
var timeleft = 15;
var downloadTimer;
function timer() {
downloadTimer = setInterval(function () {
if (timeleft <= 0) {
clearInterval(downloadTimer);
document.getElementById("countdown").innerHTML = "Finished";
} else {
document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
}
timeleft -= 1;
}, 1000);
}
function timerstop() {
clearInterval(downloadTimer);
}

Javascript clearInterval is not having an effect?

I am trying to do a simple redirect after x seconds on a page with a countdown timer. Every time I call the function I want the timer to be reset, however when i call it a second or third time the timer seems to have 3 different countdowns. Can anyone see why this is?
function delayRedirect(){
document.getElementById('countDown').innerHTML = 'Session Timeout In: <span id="countTimer"></span> seconds....';
clearInterval(sessionTimer);
var sessionTimer = null;
var timeleft = 60;
var sessionTimer = setInterval(function(){
timeleft--;
document.getElementById('countTimer').innerHTML = timeleft;
if(timeleft <= 0)
clearInterval(sessionTimer);
returnToLogin();
},1000);
}
Put the sessionTimer globally. What you currently do is re-declare sessionTimer every time you enter delayRedirect.
Working example:
const but = document.getElementById("but");
but.addEventListener("click", delayRedirect);
//define it globally
var sessionTimer = -1;
function delayRedirect() {
//clear it if it previously exists
clearInterval(sessionTimer);
sessionTimer = setInterval(function() {
console.log("sessionTimer " + sessionTimer);
}, 1000);
}
<button id="but">Run</button>
I feel like all the answers only address the Y part, not the X part, given that this is clearly an XY problem.
While the solution is to use a variable that isn't local to the function, solving the actual problem doesn't require clearing anything. One can simply use an interval to tick down, and reset the count to delay the redirect:
var timeleft = 60;
setInterval(function() {
if (--timeleft === 0) returnToLogin();
countTimer.innerHTML = timeleft;
}, 1000);
delay.onclick = function() {
timeleft = 60;
}
function returnToLogin() {
console.log("returning to login");
}
<p>Session Timeout In: <span id="countTimer">60</span> seconds....</p>
<button id="delay">Delay</button>

setInterval recount?

var sec = 10
var timer = setInterval(function() {
$('#timer span').text(sec--);
if (sec == -1) {
clearInterval(timer);
} }, 1000);
html
<div id="timer"><span>10</span> seconds</div>
Recount
What I want to do when I click recount is to recount back to 10 seconds the timer?
How can I possibly done it?
It is better to use setInterval() or setTimeout()?
Factor out your code into functions so you can call the same code on startup or when the link is clicked. You can see it working here: http://jsfiddle.net/jfriend00/x3S7j/. This even allows you to click the link during the countdown and it will start over.
$("#recount").click(function() {
initCounter(10);
});
var remainingTime;
var runningInterval = null;
function initCounter(duration) {
function stopCounter() {
if (runningInterval) {
clearInterval(runningInterval);
runningInterval = null;
}
}
stopCounter(); // stop previously running timer
remainingTime = duration; // init duration
$('#timer span').text(remainingTime); // set initial time remaining
runningInterval = setInterval(function() { // start new interval
$('#timer span').text(remainingTime--);
if (remainingTime < 0) {
stopCounter();
}
}, 1000);
}
initCounter(10);
You can just add a click handler and factor out your code in a separate method:
var sec = 10;
var timer;
function startCountdown() {
if (timer) clearInterval(timer);
sec = 10;
timer = setInterval(function() {
$('#timer span').text(sec--);
if (sec == -1) {
clearInterval(timer);
}
}, 1000);
}
$(function() {
startCountdown();
$("#recount").click(startCountdown);
});
Working JSFiddle
When you click recount, you should
sec = 10;
clearInterval(timer);
timer = setInterval(that_function, 1000);
Also, there's a difference between setInterval and setTimeout. setInterval schedules the function to be called every some milliseconds. setTimeout schedules the function to be called once, after some milliseconds.

Categories

Resources