Pause / Resume jQuery Countdown Timer - javascript

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

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.

Starting timer when clicking first card of memory game

Ok I am trying to wrap up a project and the only thing holding me back is it that they call for the timer to start on clicking a match game. The timer starts when the HTML file loads which is not what the project wants and I have tried some methods but ends up freezing the game. I want the timer to be able to start when clicking a card.
var open = [];
var matched = 0;
var moveCounter = 0;
var numStars = 3;
var timer = {
seconds: 0,
minutes: 0,
clearTime: -1
};
//Start timer
var startTimer = function () {
if (timer.seconds === 59) {
timer.minutes++;
timer.seconds = 0;
} else {
timer.seconds++;
};
// Ensure that single digit seconds are preceded with a 0
var formattedSec = "0";
if (timer.seconds < 10) {
formattedSec += timer.seconds
} else {
formattedSec = String(timer.seconds);
}
var time = String(timer.minutes) + ":" + formattedSec;
$(".timer").text(time);
};
This is the code for clicking on a card. I have tried to include a startTimer code into this but doesn't work.
var onClick = function() {
if (isValid( $(this) )) {
if (open.length === 0) {
openCard( $(this) );
} else if (open.length === 1) {
openCard( $(this) );
moveCounter++;
updateMoveCounter();
if (checkMatch()) {
setTimeout(setMatch, 300);
} else {
setTimeout(resetOpen, 700);
}
}
}
};
And this class code I use for my HTML file
<span class="timer">0:00</span>
Try this: https://codepen.io/anon/pen/boWQbe
All you needed to do was remove resetTimer() call from the function that happens on page load and then just do a check in the onClick (of card) to see if the timer has started yet. timer.seconds == 0 && timer.minutes == 0.

JS countdown timer - Pause function

Here's a simple countdown timer that counts from 9 down to 0.
The countdown works fine. But what if I want to pause it mid-flow and then restart from where it was paused?
I have tried (see code below) to interrupt the countdown, save the number it was at, and then restart the function from the new number. But the countdown goes haywire, and I can't see why. Any ideas?
PS. I could cut and paste a timer from elsewhere, but I'm doing this for the learning experience. I'm sure there are better ways to code a countdown timer in JS, but it's bugging me that I can't make THIS way work and think I must be missing something obvious.
Many thanks
var currentTimeInt = 10;
var minn = [];
var stop = 0;
// stop
function stopCounter() {
currentTime = document.getElementById('mins').textContent; // grabs the number of minutes at moment of pause.
stop = 1;
}
// restart
function restart() {
stop = 0;
currentTimeInt = parseInt(currentTime, 10); // converts that number into an integer we can use
document.getElementById("mins").innerHTML=currentTimeInt;
newMinutes(); // restarts the newMinutes function with the start time currentTimeInt set to the time the counter stopped at
}
function newMinutes() {
document.getElementById('mins').innerHTML= currentTimeInt; // displays the counter
for (aa = currentTimeInt-1; aa >= 0; aa--) {
minn.push(aa); // builds an array of numbers in descending order
document.getElementById('mins').innerHTML= minn[aa];
for (let bb=1; bb<=currentTimeInt; bb++) {
if (bb<currentTimeInt) {
setTimeout( function timer(){
if (stop == 0) { // checks if "stop!" has been clicked and returns false to stop the function if that is the case
document.getElementById('mins').innerHTML= minn[bb];
console.log(minn[bb]);
}
else {return false;}
}, bb*1000 );
}
}
}
console.log(currentTimeInt + " the end");
}
<span>Minutes: </span><span id= "mins"></span>
<button onclick="newMinutes()">Go!</button>
<button onclick="stopCounter()">Stop!</button>
<button onclick="restart()">Reset!</button>
You may try this as an example:
var timerId;
var counter;
function start() {
console.log('start');
if (!counter) {
reset();
} else {
loop();
}
}
function pause() {
console.log('pause');
if (timerId) {
clearInterval(timerId);
timerId = null;
}
}
function reset() {
console.log('reset');
pause();
counter = 10;
loop();
}
function loop() {
timerId = setInterval(function() {
if (0 >= counter) {
pause();
return;
}
console.log('counter', counter);
counter--;
}, 500);
}
<button onclick='start();'>Start</button>
<button onclick='pause();'>Pause</button>
<button onclick='reset();'>Reset</button>
Here is my little Countdown with START, PAUSE, RESUME, STOP & RESET features:
var jqcd_start_id = 'input#jqcd_start';
var jqcd_time_id = 'input#jqcd_time';
var jqcd_count_id = 'span#jqcd_count';
var jqcd_end_message = 'Time is up!';
var jqcd_countdown = '';
var jqcd_status = 'stopped';
var jqcd_current = '';
function jqcd(action){
if (action == 'start') {
if (jqcd_status == 'stopped') {
jqcd_updtv(jqcd_start_id, 'Pause');
jqcd_status = 'running';
jqcd_current = jqcd_countdown;
jqcd_updtt(jqcd_count_id, jqcd_countdown);
}
else if (jqcd_status == 'running') {
jqcd_updtv(jqcd_start_id, 'Resume');
jqcd_status = 'paused';
}
else if (jqcd_status == 'paused') {
jqcd_updtv(jqcd_start_id, 'Pause');
jqcd_status = 'running';
}
}
else if (action == 'stop') {
jqcd_updtv(jqcd_start_id, 'Start');
jqcd_status = 'stopped';
jqcd_updtt(jqcd_count_id, jqcd_end_message);
}
else if (action == 'reset') {
jqcd_updtv(jqcd_start_id, 'Start');
jqcd_status = 'stopped';
jqcd_updtt(jqcd_count_id, jqcd_countdown);
}
var a = jqcd_current.split(":");
var m = a[0];
var s = (a[1] - 1);
if (s < 0) {
if (parseInt(m) == 0) {
jqcd_updtv(jqcd_start_id, 'Start');
jqcd_status = 'stopped';
jqcd_updtt(jqcd_count_id, jqcd_end_message);
}
else {
m = m - 1;
s = 59;
}
}
if(s >= 0){
setTimeout(function(){
if (jqcd_status == 'running') {
m = (parseInt(m) < 10)? "0" + parseInt(m): m;
s = (parseInt(s) < 10)? "0" + parseInt(s): s;
jqcd_updtt(jqcd_count_id, m + ":" + s);
jqcd_current = m + ":" + s;
jqcd('');
}
}, 1000);
}
}
function jqcd_updtv(selector, value) {
if (selector != '') {
$(selector).val(value);
}
}
function jqcd_updtt(selector, value) {
if (selector != '') {
$(selector).text(value);
}
}
$(document).ready(function() {
jqcd_countdown = $(jqcd_time_id).val();
jqcd_updtt(jqcd_count_id, jqcd_countdown);
$(jqcd_time_id).keyup(function() {
jqcd_countdown = $(jqcd_time_id).val();
jqcd_updtt(jqcd_count_id, jqcd_countdown);
jqcd_updtv(jqcd_start_id, 'Start');
jqcd_status = 'stopped';
});
});
span#jqcd_count {
font-size: 20pt;
font-weight: bold;
}
input#jqcd_start,
input#jqcd_stop,
input#jqcd_reset {
font-size: 12pt;
font-weight: bold;
}
input#jqcd_start,
input#jqcd_stop,
input#jqcd_reset {
width: 100px;
}
span#jqcd_count {
font-family: "Lucida Console", Monaco, "Courier New", Courier, monospace !IMPORTANT;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="jqcd_count">00:30</span><br><br>
<input type="button" id="jqcd_start" value="Start" onClick="jqcd('start')" />
<input type="button" id="jqcd_stop" value="Stop" onClick="jqcd('stop')" />
<input type="button" id="jqcd_reset" value="Reset" onClick="jqcd('reset')" /><br><br>
<input type="text" id="jqcd_time" value="00:10" />
<br><br>
It is pretty simple to customize. The first four variables in the JavaScript code can be adapted to work with your specific HTML.
If you want an action to take place every second, add your lines of code inside of the "jqcd_updtt" function.
The CSS is completely optional, of course.
The Countdown start time is set dynamically by altering the value in the "jqcd_time" field. If, however, you want to set a static value for the Countdown starting point, you can alter the variables inside the "$(document).ready(function() {" function at the end of the JavaScript code.
PS.
This Countdown has no maximum limit for minutes or seconds
What about keeping it KISS!
let i = 9,j
function chrono(){
if (i>=0){
now.innerText = i--
}
}
<h1><div id="now">⏰ Ready!</div>
<button onclick="setInterval(function(){ chrono() }, 1000);this.style.display='none'">Start</button>
<button onclick="i=10">Reset</button>
<button onclick="j=i;i=-1">Pause</button>
<button onclick="i=j">Continue</button>
This is the most basic example ready to be expanded, mostly there is no clearInterval.
The KISS principle states that most systems work best if they are kept
simple rather than made complicated; therefore simplicity should be a
key goal in design and unnecessary complexity should be avoided.
https://en.wikipedia.org/wiki/KISS_principle
Therefore, js incrementation and setInterval seems easy but they hide complex things.
An other approach using date.now() that provide an accurate unix timestamp based on the system clock, and the web audio api for beeping.
i = Date.now();j=i+10000;z.innerText="Target #"+j
function d(){
if(now.innerText < j){
now.innerText = Date.now()
k(3,603,80)
}
if(now.innerText > j){
now.innerHTML = "<b>TIME TRAVEL COMPLETE!</b>"
k(8,728,100)
}
}
setInterval(function(){ d() }, 100)
a=new AudioContext()
function k(w,x,y){
v=a.createOscillator()
u=a.createGain()
v.connect(u)
v.frequency.value=x
v.type="square"
u.connect(a.destination)
u.gain.value=w*0.01
v.start(a.currentTime)
v.stop(a.currentTime+y*0.001)
}
EPOCH: <out id="now"></out><h6 id="z">
The first issue here is that currentTime isn't globally defined, so it can't be accessed from within restart. Just put var currentTime; at the start of your file.
But you have another serious breaking issue in that you're using setTimeout in a really awkward way. You're creating multiple timeouts all at once and giving them a delay based on their relation tocurrentTimeInt. This has two problems. For one the use of two for loops isn't very efficient and also seems redundant as your inner for loop is just going to count up to the currentTimeInt anyway.
Secondly, you never clear (and probably won't be able to clear) the timeouts. That means when you restart your timer after pausing if any timeouts hadn't yet been fired, then your program will run those and make the minutes jump back and forth between the old timeouts and the new ones you create after unpausing.
I know in your comment you said you wanted to get this to work because you basically did the whole thing yourself, but it may not be worth continuing down this road. After looking at it some I think fixing your program would require it to be restructured, or else require it to be hacked in a way that makes it pretty inefficient. And if you're someone who's just learning Javascript, it's probably better to just start over and do it the right way anyway.
Below is an example of a better way using setInterval rather than setTimeout, but feel free to just try and figure it out on your own.
(There are ways you can improve the functionality of the code below, but it should be enough to get you the general idea)
var startTimeInt = 10;
var currentTimeInt = startTimeInt;
var interval = undefined;
// start the timer
function startCounter() {
if(!interval){
document.getElementById('mins').innerHTML = currentTimeInt;
interval = setInterval(newNumber, 1000) // set an interval
}
}
// stop
function stopCounter() {
// clear the interval
clearInterval(interval)
interval = undefined;
}
// reset the timer
function resetCounter(){
currentTimeInt = startTimeInt;
document.getElementById('mins').innerHTML = currentTimeInt;
//stopCounter(); startCounter();
}
// change the time and handle end of time event
function newNumber(){
currentTimeInt--; // decrement the current time
document.getElementById('mins').innerHTML = currentTimeInt;
if(currentTimeInt == 0){
console.log("Done");
stopCounter();
}
}
<span>Minutes: </span><span id= "mins"></span>
<button onclick="startCounter()">Go!</button>
<button onclick="stopCounter()">Stop!</button>
<button onclick="resetCounter()">Reset!</button>
Here is a working Snippet..
var paused = false;
var started = false;
var stopped = true;
var currentCount = 0;
var running = false;
interval = 1000;
maxCount = 10;
function start() {
if (stopped){
started = true;
paused= false;
stopped = false;
currentCount = maxCount;
loop(); running = true;
return;
}
paused= false;
}
function pause() {
paused= true;
}
function stop(){
paused = false;
started = false;
stopped = true;
running = false;
currentCount = 0;
}
function update(item){
document.getElementById("status").innerHTML = item;
//console.log(item);
--currentCount;
if(currentCount < 0){stop()}
}
function reset() {
currentCount = maxCount;
document.getElementById("status").innerHTML = currentCount;
}
function loop(){
if (!stopped){
if (!paused){update(currentCount);}
setTimeout(function(){loop()}, interval)
}
}
<button onclick='start();'>Start</button>
<button onclick='pause();'>Pause</button>
<button onclick='reset();'>Reset</button>
<button onclick='stop();'>Stop</button>
<div id="status"></div>
for anyone who want to re-use the code, simply change the value of timer and the render function to fit your project
var timer= 10;
var intervalID
// pause/stop
function stopTimer() {
clearInterval(intervalID);
intervalID= null;
}
// restart
function restart() {
stopTimer();
timer= 10;
render();
// Go(); //Optional
}
// start/resume
function Go() {
if(intervalID){
//if interval already created previously, exit function
return
}
intervalID = setInterval(
() => {
if(timer< 1){
//escape from interval so that counter dont go below 0
return stopTimer();
}
timer--;
render();
}, 1000); //1000 milisecond == 1 second
}
function render(){
// it is ok to run render redundantly as it does not mutate the data
// feel free to change this to fit your needs
console.log(timer);
document.getElementById("mins").innerHTML=timer;
}
render() //render once on load
<span>Minutes: </span><span id= "mins"></span>
<button onclick="Go()">Go!</button>
<button onclick="stopTimer()">Stop!</button>
<button onclick="restart()">Reset!</button>

Enable button when counter reaches zero

I have a button its disabled and i want to put a counter inside it, what i want to do is when the counter reaches zero it get enabled, how can i do that? in the code below the counter doesn't appear inside the button and i don't want the reset button i just want the button to be enabled when it reaches zero, here is what i have tried so far:
function Countdown()
{
this.start_time = "00:30";
this.target_id = "#timer";
this.name = "timer";
this.reset_btn = "#reset";
}
Countdown.prototype.init = function()
{
this.reset();
setInterval(this.name + '.tick()',1000)
}
Countdown.prototype.reset = function()
{
$(this.reset_btn).hide();
time = this.start_time.split(":");
//this.minutes = parseInt(time[0]);
this.seconds = parseInt(time[1]);
this.update_target();
}
Countdown.prototype.tick = function()
{
if(this.seconds > 0) //|| this.minutes > 0)
{
if(this.seconds == 0)
{
// this.minutes = this.minutes - 1;
this.seconds = 59
} else {
this.seconds = this.seconds - 1;
}
}
this.update_target()
}
Countdown.prototype.update_target = function()
{
seconds = this.seconds;
if (seconds == 0) $(this.reset_btn).show();
else if(seconds < 10) seconds = "0" + seconds;
$(this.target_id).val(this.seconds)
}
timer = new Countdown();
timer.init();
$(document).ready(function(){
$("#reset").click(function(){
//timer = new Countdown();
timer.reset();
});
});
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="text" id="timer" disabled>Counter should be inside me, and enable me when it reaches 0</button>
<button id="reset">Reset</button>
This is much simpler than what you've got. Just use window.setTimeout().
Keep in mind that tracking time to a high precision is not super reliable in a browser. You may want to look at moment.js or use performance.now() for an easier API to handle that.
// Get refreence to span and button
var spn = document.getElementById("count");
var btn = document.getElementById("btnCounter");
var count = 5; // Set count
var timer = null; // For referencing the timer
(function countDown(){
// Display counter and start counting down
spn.textContent = count;
// Run the function again every second if the count is not zero
if(count !== 0){
timer = setTimeout(countDown, 1000);
count--; // decrease the timer
} else {
// Enable the button
btn.removeAttribute("disabled");
}
}());
<button id="btnCounter" disabled>Time left: <span id="count"></span></button>

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