I have a timer running using jquery setInterval and a button that toggles between play and pause. I need the timer to pause and/or continue running when the user clicks on the play/pause button. Also, for some reason, the seconds goes from "59" to "01". It's skipping "00". I'm not sure why. Thanks for your help!
HTML:
<div id="clock">0:00</div>
<div id="audioBtn">
<div class="btn play"></div>
<div class="btn pause"></div>
</div>
JQuery
var output = $('#clock');
var isPaused = false;
var min = 0;
var sec = 0;
var t = window.setInterval(function() {
if(!isPaused) {
sec++;
if (sec < 10) {
output.html(min + ":0" + sec);
} else {
output.html(min + ":" + sec);
}
if (sec === 59) {
sec = 0;
min++;
}
}
}, 1000);
if ($('.btn').hasClass('pause')) {
$('#audioBtn').on('click', function(e) {
e.preventDefault();
console.log("should pause");
isPaused = true;
});
};
if ($('.btn').hasClass('play')) {
$('#audioBtn').on('click', function(e) {
e.preventDefault();
console.log("should play");
isPaused = false;
});
};
change it to
if (sec == 59) {
sec = -1;
min++;
}
Related
I'm just starting with javascript, I've been trying to make a simple stopwatch, I found a couple of ways to do it , then I came across this function ... the code doesn't work as a stopwatch unless we return a function , can somebody help me understand why????
for (var i = 1; i <= 5; i++) {
var tick = function(i) {
return ()=>{console.log(i);}
};
setTimeout(tick(i), 500 * i);
}
You should use setInterval and clearInterval for your case.
var i = 10;
var tick = function(i) {
return ()=>{
console.log(i--);
if(i == 0) clearInterval(timer);
}
};
var timer = setInterval(tick(i), 500);
If you want to have stopwatch, you can clearInterval in stop button click event
function stop(){
clearInterval(timer);
}
Update:
I combined Start and Stop in only one button using addEventListener and removeEventListener
var i = 1;
var timer;
var tick = function(i) {
return ()=>{
console.clear();
console.log(i++);
//if(i == 0) clearInterval(timer);
}
};
function start(){
document.getElementById("start").disabled = true;
document.getElementById("stop").disabled = false;
timer = setInterval(tick(i), 500);
}
function stop(){
clearInterval(timer);
document.getElementById("stop").disabled = true;
document.getElementById("start").disabled = false;
}
(function() {
document.getElementById("start2").addEventListener("click", start2);
})();
function start2(){
timer = setInterval(tick(i), 500);
document.getElementById("start2").innerHTML = "Stop";
document.getElementById("start2").removeEventListener("click", start2);
document.getElementById("start2").addEventListener("click", stop2);
}
function stop2(){
clearInterval(timer);
document.getElementById("start2").innerHTML = "Start";
document.getElementById("start2").removeEventListener("click", stop2);
document.getElementById("start2").addEventListener("click", start2);
}
<button id="start" onclick="start()">Start</button>
<button id="stop" onclick="stop()">Stop</button>
<h2>Combine Start and Stop</h2>
<button id="start2" >Start</button>
Because setTimeout first parameter has to be a function.
Your code works because it immediately executes the tick(i) function, which returns a function and that one is used 500ms later as callback.
below code will help you
<h1><time>00:00:00</time></h1>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
</pre>
<script>
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);
}
start.onclick = function(){
timer();
start.disabled=true;
}
/* Stop button */
stop.onclick = function() {
clearTimeout(t);
start.disabled=false;
}
/* Clear button */
clear.onclick = function() {
h1.textContent = "00:00:00";
seconds = 0; minutes = 0; hours = 0;
}
</script>
I'm working with the following script for a count-up timer. It has no problem counting up in seconds but I'm having trouble getting it to display minutes. For example 1:35 (one minute and 35 seconds)
Any suggestions would be appreciated. Thanks in advance.
var clicked = false;
var sec = 00;
var min = 00;
function startClock() {
if (clicked === false) {
clock = setInterval("stopWatch()", 1000);
clicked = true;
} else if (clicked === true) {}
}
function stopWatch() {
sec++;
document.getElementById("timer").innerHTML = sec;
}
function stopClock() {
window.clearInterval(clock);
sec = 0;
document.getElementById("timer").innerHTML = 0;
clicked = false;
}
var min = 0;
var second = 00;
var zeroPlaceholder = 0;
var counterId = setInterval(function() {
countUp();
}, 1000);
function countUp() {
second++;
if (second == 59) {
second = 00;
min = min + 1;
}
if (second == 10) {
zeroPlaceholder = '';
} else
if (second == 00) {
zeroPlaceholder = 0;
}
document.getElementById("count-up").innerText = min + ':' + zeroPlaceholder + second;
}
<div class="timer">
<div id="timer">0:00</div>
<input type="button" id="btnParentButton" value="start timer" onClick="startClock()"/>
Hope this can help you.
The better way is to have your minutes and secs as global variable and simple function for each button
EDIT
Update code using pure JS
var min = 0;
var sec = 0;
var timer = undefined;
var isStarted = false;
function startcount(){
sec++;
if(sec==60)
{
sec=0;
min++;
}
updateClock();
}
function updateClock(){
var displaySec = sec < 10 ? "0" + sec : sec;
var displayMin = min < 10 ? "0" + min : min;
document.getElementById("count").innerHTML = displayMin + " : " + displaySec;
}
function start(){
if(timer == undefined || !isStarted){
timer = setInterval(function(){
startcount();
},1000);
}
isStarted = true;
}
function stop(){
isStarted = false;
clearInterval(timer);
}
function reset(){
stop();
min=sec=0;
timer = undefined;
updateClock();
}
updateClock();
<div id="count"></div>
<button class="start" onClick="start()">Start</button>
<button class="stop" onClick="stop()">Stop</button>
<button class="reset" onClick="reset()">Reset</button>
Put count-up instead id=timer
var clicked = false;
var sec = 00;
var min = 00;
function startClock() {
if (clicked === false) {
clock = setInterval("stopWatch()", 1000);
clicked = true;
} else if (clicked === true) {}
}
function stopWatch() {
sec++;
document.getElementById("timer").innerHTML = sec;
}
function stopClock() {
window.clearInterval(clock);
sec = 0;
document.getElementById("timer").innerHTML = 0;
clicked = false;
}
var min = 0;
var second = 00;
var zeroPlaceholder = 0;
var counterId = setInterval(function() {
countUp();
}, 1000);
function countUp() {
second++;
if (second == 59) {
second = 00;
min = min + 1;
}
if (second == 10) {
zeroPlaceholder = '';
} else
if (second == 00) {
zeroPlaceholder = 0;
}
document.getElementById("count-up").innerText = min + ':' + zeroPlaceholder + second;
}
<div class="timer">
<div id="count-up">0:00</div>
<input type="button" id="btnParentButton" value="start timer" onClick="startClock()"/>
I am trying to get this script to count up to a specified number and back down to a specified number as follows: 19200, 38400, 57600, 76800, 96000, 76800, 57600, 38400, 19200 — repeatedly. So far this is what I have but I cannot seem to make it count down in the order above, it restarts from 19200 again.
$(function() {
var seconds = 19200;
var timerId = setInterval(function() {
seconds = seconds + 19200;
$("#counter").text(seconds);
if (seconds > "76800") {
clearInterval(seconds);
seconds = seconds - "19200";
}
}, 500);
});
A little issue with the logic, the condition
if (seconds > "76800") {
would always try to keep the seconds above 76800.
Rather you would want a flag to track the direction of the count. Check out below:
UPDATED:
Working demo at
JSFiddle
$(function () {
var increment = 19200;
var seconds = increment;
var countUp = true;
var timerId = setInterval(function () {
$("#counter").text(seconds);
if (countUp) {
seconds += increment;
} else {
seconds -= increment;
}
if (countUp && seconds > increment*4) {
countUp = false;
} else if (!countUp && seconds <= increment) {
countUp = true;
}
}, 500);
});
Check the below function
$(function() {
var seconds = 19200;
action = 'add';
var timerId = setInterval(function() {
$("#counter").text(seconds);
if (seconds == 96000) {
action = 'remove';
} else if (seconds == 19200) {
action = 'add'
}
if (action == 'add')
seconds += 19200;
else if (action == 'remove')
seconds -= 19200;
}, 500);
});
I think this is a little more elegant
var increment = 19200,
seconds = increment;
var timer = setInterval(function() {
console.log(seconds);
seconds += increment;
if (seconds > 76800 || seconds < 19200) {
increment *= -1;
}
}, 500);
jsfiddle
http://jsfiddle.net/Bwdfw/98/
is there a way to start timer only after a button is clicked in the given jsfiddle link
http://jsfiddle.net/Bwdfw/98/
var seconds=0;
var Score=0;
var index=0;
countdown(60);
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if(seconds>60 && Score<30)
{
alert("Not enough Score");
}
if( seconds > 0 ) {
setTimeout(tick, 1000);
}
}
Have a function inside the click handler and a variable which states if the function has started or not.
Also you can club the click events inside a single handler and the index can be stored as part of the data-* attributes which reduces duplicated code.
Javascript
//Timer //
var seconds = 0,
Score = 0,
index = 0,
timerStarted = false;
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if (seconds > 60 && Score < 30) {
alert("Not enough Score");
}
if (seconds > 0) {
setTimeout(tick, 1000);
}
}
$("#one, #two, #three").click(function () {
if(!timerStarted) {
countdown(60);
timerStarted = true;
}
var dataIndex = $(this).data('index');
if (index == dataIndex) {
Score++;
if(dataIndex == 2) {
index = 0;
} else {
index++;
}
}
$("#score").html("Score: " + Score);
});
HTML
<div id="timer"></div>
<div id="score">Score: 0</div>
<button id="one" type="button" data-index="0">Button1</button>
<button id="two" type="button" data-index="2">Button2</button>
<button id="three" type="button" data-index="1">Button3</button>
Check Fiddle
var seconds=0;
var Score=0;
var index=0;
var started = false;
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if(seconds>60 && Score<30)
{
alert("Not enough Score");
}
if( seconds > 0 ) {
setTimeout(tick, 1000);
}
}
$("button").click(function(){
if(!started){
started = true;
countdown(60);
}
});
You could generate custom event after click
$(window).trigger('clicked');
$(window).on('clicked', function() {
setTimeout(tick, 1000);
});
http://jsfiddle.net/Bwdfw/100/
Just remember to check if the countdown has not started yet.
$("button").click(function(){
});
This will add a handler to all the buttons in your DOM, then just check the status of the countdown.
Check this fiddle:
http://jsfiddle.net/eddiarnoldo/Bwdfw/102/
I am trying to create a timeout on my webpage by counting down from 1min to 0 seconds, then displaying a message. If the user moves the mouse (i.e is still active on the page) the timer gets reset. I cant get the reset function to reset my values. What it is doing is counting down the time faster than before and getting stuck in an unbreakable cycle.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
var mins = 1;
var secs = 0;
var timer;
function start()
{
timer = setInterval("update()", 1000);
}
function reset() {
var mins = 1
var secs = 0;
var timer;
start();
}
function update()
{
var timeField = document.getElementById("time");
if (secs == 0)
{
if (mins == 0)
{
timeField.innerHTML = "Time's up!";
clearInterval(timer);
alert("Time's up");
return;
}
mins--;
secs = 59;
}
else
{
secs--;
}
if (secs < 10)
{
timeField.innerHTML = 'Time left: ' + mins + ':0' + secs;
}
else
{
timeField.innerHTML = 'Time left: ' + mins + ':' + secs;
}
}
</script>
</head>
<body onload="start();" onmousemove="reset();">
<div id="time" >
</div>
</body>
</html>
How can I get it to reset the countdown and start again? I am new to javascript so please be patient.
Modify your reset function,
function reset() {
mins = 1;
secs = 0;
window.clearInterval(timer);
start();
}
Declare timer outside of all functions.