How to set one minute counter in javascript? - 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>

Related

How do I start a timer on a click?

I'm trying to have a timer start when the user makes the first click on a page. Been doing a lot of research and for the life of me, can't figure it out. I think I should use a document.addEventListener but am not sure where it goes.
let min = 0;
let sec = 0;
function myTimer() {
if (counting) {
timer.innerHTML = min + " minutes " + sec + " seconds";
sec++;
if (sec >= 60) {
sec = 0;
min++;
}
}
}
//Start the timer
let startTimer = setInterval(function() {
myTimer();
}, 1000);
Just add a click listener to document that calls the setInterval:
let min = 0;
let sec = 0;
function myTimer() {
timer.innerHTML = min + " minutes " + sec + " seconds";
sec++;
if (sec >= 60) {
sec = 0;
min++;
}
}
//Start the timer
document.addEventListener('click', () => {
setInterval(myTimer, 1000);
}, { once: true });
<div id="timer">click somewhere</div>
Given a button with id button as so:
<button id="button">Click me</button>
the most basic way to add an event listener for that button to start the timer is by retrieving the element from dom (using querySelector or getElementById), then add a named event listener function to the element in the dom, such as onclick:
document.querySelector('#button').onclick = function(){
//your code to start timeer here
};
but you can also do it using addEventListener:
document.querySelector('#button').addEventListener('click',function(){
//your code to start timeer here
});
or with event delegation, you can add a global click handler to the document, check if the target element was the button, and if so you can then start the timer:
document.addEventListener('click',function(event){
if(event.target.id==='button'){
//your code to start timer here
}
});
there are 900 ways to skin a cat in modern javascript, its up to you to decide which one is most appropriate, and sometimes its a matter of personal preference.

Javascript Second into Minutes:Seconds

I am working on a clock that needs to display seconds into a
minutes:seconds
format.
I have worked on some auxiliary functions for display, but I have never really gotten the full display. Here is some of my code:
var time = 1500;
//Must declare timeHandler as global variable for stopTimer()
var timeHandler;
//Set intial HTML to time
document.getElementById("timer").innerHTML = display;
//Timer function for start button
function timer() {
timeHandler = setInterval(function() {
if (time > 0) {
time--;
document.getElementById("timer").innerHTML = time;
}
}, 1000);
}
//Stop function for stop button
function stopTimer() {
clearTimeout(timeHandler);
}
//Timer Display
var minutes = time/60;
var second = time%60;
var display = minutes + ":" + seconds;
HTML:
<h1> Pomodoro Clock</h1>
<!--Place holder for timer-->
<div id="timer" class="circle">Timer</div>
<!--//Start Button-->
<button onclick="setTimeout(timer, 1000);">Start</button>
<!--Stop Button-->
<button onclick="stopTimer()">Stop</button>
Thie formatTime function below will take a number of seconds, and convert it to MM:SS format (including padded zeroes):
var time = 1500;
//Must declare timeHandler as global variable for stopTimer()
var timeHandler;
//Set intial HTML to time
document.getElementById("timer").innerHTML = display;
//Timer function for start button
function timer() {
timeHandler = setInterval(function() {
if (time > 0) {
time--;
document.getElementById("timer").innerHTML = formatTime(time);
}
}, 1000);
}
//Stop function for stop button
function stopTimer() {
clearTimeout(timeHandler);
}
function formatTime(seconds) {
//Timer Display
var minutes = seconds / 60;
var second = seconds % 60;
return ('0'+minutes).substr(-2) +":"+ ('0'+seconds).substr(-2);
}
first of all you have to use clearInterval, then you don't update your display every second
check this fiddle out

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;
});

Reset javascript function

I am having trouble getting a javascript function to reset itself after an onclick event. When I click the "Start" button the counter begins to count up. But when I click the "Reset" button nothing happens. I need the timer to reset to "0:00" and wait for me to click "Start" again. Here is my code:
<script type="text/javascript">
var seconds = 0;
var minutes = 0;
function zeroPad(time) {
var numZeropad = time + '';
while(numZeropad.length < 2) {
numZeropad = "0" + numZeropad;
}
return numZeropad;
}
function countSecs() {
seconds++;
if (seconds > 59) {
minutes++;
seconds = 0;
}
document.getElementById("timeBox").innerHTML = "Time " + zeroPad(minutes) + ":" + zeroPad(seconds);
}
function startTimer() {
action = window.setInterval(countSecs,1000);
}
function resetTimer() {
var seconds = 0;
var minutes = 0;
}
</script>
<body>
<button onclick = "startTimer()">Start</button>
<div id="timeBox">Time 00:00</div>
<button onclick = "resetTimer">Reset</button>
</body>
Call the clearInterval() method.
function resetTimer() {
window.clearInterval(action);
}
This is a scoping issue, using var inside a function, makes seconds and minutes local to that function. Removing the leading var will start you off in the right direction.
function resetTimer() {
seconds = 0;
minutes = 0;
}
Onclick events must call functions like: onclick="resetTimer();" with the parenthesis at the end. Some browsers may try to submit on button clicks if you don't define type="button". I didn't assume you wanted reset timer to stop the timer so I added a stop button.
http://jsfiddle.net/iambriansreed/WRdSK/
<button type="button" onclick="startTimer();">Start</button>
<div id="timeBox">Time 00:00</div>
<button type="button" onclick="resetTimer();">Reset</button>
<button type="button" onclick="stopTimer();">Stop</button>
<script>
window.seconds = 0;
window.minutes = 0;
function startTimer() {
window.action = setInterval(countSecs,1000);
}
function resetTimer() {
seconds = 0;
minutes = 0;
}
function stopTimer() {
clearInterval(action);
seconds = -1;
minutes = 0;
countSecs();
}
function zeroPad(time) {
var numZeropad = time + '';
while(numZeropad.length < 2) {
numZeropad = "0" + numZeropad;
}
return numZeropad;
}
function countSecs() {
seconds++;
if (seconds > 59) {
minutes++;
seconds = 0;
}
document.getElementById("timeBox").innerHTML = "Time " + zeroPad(minutes) + ":" + zeroPad(seconds);
}
</script>
​
You have two errors in your code:
First, in the button you missed the () after the function's name in order to make an actual call:
<button onclick = "resetTimer()">Reset</button>
Second, you did not stop the interval using window.clearInterval() (MDN docu), so the timer went on and on.
// just to make it an explicit global variable. already was an implicit one.
var action;
// rest of your code
function resetTimer() {
// clear the timer
window.clearInterval( action );
// reset variables
var seconds = 0;
var minutes = 0;
// update output
document.getElementById("timeBox").innerHTML = "Time " + zeroPad(minutes) + ":" + zeroPad(seconds);
}
I set up a working fiddle here.

Categories