Why is my JavaScript second counter not working? - javascript

I made a second counter in JavaScript. But my code is not working.
My problem: "First I pressed Start button, but seconds was not going on normally."
Here is my codes:
var a = 0;
var Time = setInterval(Counter, 1000);
function startCounter() {
setInterval(Counter, 1000);
}
function Counter() {
a += 1;
seconds.innerHTML = a;
}
function pauseCounter() {
clearInterval(Time);
}
function resetCounter() {
a = 0;
seconds.innerHTML = a;
}
<button onclick="startCounter()">Start</button>
<br>
<button onclick="pauseCounter()">Pause</button>
<p>Seconds: <a id='seconds'>0</a></p>
<button onclick="resetCounter()">Reset</button>

The problem in your code is following line:
setInterval(Counter, 1000);
In above line you are creating an interval but you are not assigning it to any variable. So its not being cancelled.
Before starting a new interval make sure to clear the last one.
You need to assign the new setInterval to Time each time
var a = 0;
var Time;
function startCounter() {
clearInterval(Time)
Time = setInterval(Counter, 1000);
}
function Counter() {
a += 1;
seconds.innerHTML = a;
}
function pauseCounter() {
clearInterval(Time);
}
function resetCounter() {
a = 0;
seconds.innerHTML = a;
}
<button onclick="startCounter()">Start</button>
<br>
<button onclick="pauseCounter()">Pause</button>
<p>Seconds: <a id='seconds'>0</a></p>
<button onclick="resetCounter()">Reset</button>

When you defined Time, you set it as an interval preemptively, meaning that it starts instantly. And in startCounter(), you just created an unnamed interval, which you cannot clear.
var a = 0;
var Time;
function startCounter() {
clearInterval(Time) // prevent multiple intervals at same time
Time = setInterval(Counter, 1000);
}
function Counter() {
a += 1;
seconds.innerHTML = a;
}
function pauseCounter() {
clearInterval(Time);
}
function resetCounter() {
a = 0;
seconds.innerHTML = a;
}
<body>
<script src="index.js"></script>
<button onclick="startCounter()">Start</button>
<br>
<button onclick="pauseCounter()">Pause</button>
<p>Seconds: <a id='seconds'>0</a></p>
<button onclick="resetCounter()">Reset</button>
</body>

You need to clear the interval but also use type=button and addEventListener
let a = 0;
let time;
let seconds;
window.addEventListener("load", function() {
seconds = document.getElementById("seconds");
document.getElementById("start").addEventListener("click", function() {
clearInterval(time);
time = setInterval(counter, 1000);
});
document.getElementById("pause").addEventListener("click", pauseCounter);
document.getElementById("resetBut").addEventListener("click", resetCounter);
});
function counter() {
a += 1;
seconds.innerHTML = a;
}
function pauseCounter() {
clearInterval(time);
}
function resetCounter() {
a = 0;
seconds.innerHTML = a;
}
<button type="button" id="start">Start</button>
<br>
<button type="button" id="pause">Pause</button>
<p>Seconds: <a id='seconds'>0</a></p>
<button type="button" id="resetBut">Reset</button>

You have to set the seconds object like this.
seconds = document.getElementById('seconds')

Related

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>

I created a Stopwatch in JavaScript. I would like to add a sound when a user inputs the time to be reminded

I am a newbie and trying to learn. I created a Start-stop watch in HTML and js. I would like to add an input field for the users to input time and when it hits that a sound should be played.
I tried to make a variable and try to get the input data but I only screw up everything. I tried to look for it on YouTube and Google but I couldn't seem to find any answers.
Thanks for your time. Below is my code.
<div class="controls">
<button onclick="start()">Start</button>
<button onclick="pause()">Pause</button>
<button onclick="stop()">Stop</button>
<button onclick="restart()">Restart</button>
<button onclick="lap()">Lap</button>
<button onclick="resetLaps()">Reset Laps</button>
</div>
<div class="stopwatch">
00:00:00
</div>
<input type="text" id="inputVal"><button onclick="getVal()">Set Time</button>
<ul class="laps"></ul>
<audio id="ado" src="http://static1.grsites.com/archive/sounds/musical/musical009.mp3" controls="true"></audio>
Below is the Javascript.
<script type="text/javascript">
var ms = 0, s = 0, m = 0;
var timer;
var stopwatchEL = document.querySelector('.stopwatch');
var lapsContainer = document.querySelector('.laps');
function start(){
if(!timer){
timer = setInterval(run, 10)
}
}
function run(){
stopwatchEL.textContent = getTimer();
ms++;
updateTimer();
if(ms == 100){
ms = 00;
s++
}
if(s == 60){
s = 0;
m++;
}
}
function pause(){
stopTimer();
}
function stop(){
stopTimer();
m = 0;
ms = 0;
s = 0;
stopwatchEL.textContent = getTimer();
}
function getTimer(){
return (m < 10 ? "0" + m:m) + ":" + (s < 10 ? "0" + s:s) + ":" + (ms < 10 ? "0" + ms:ms);
}
function stopTimer(){
clearInterval(timer);
timer = false;
}
function restart(){
stop();
start();
}
function lap(){
if(timer){
var li = document.createElement('li');
li.innerText = getTimer();
lapsContainer.appendChild(li);
}
}
function resetLaps() {
lapsContainer.innerHTML = "";
}
function getVal(){
var inputVal = document.getElementById('inputVal').value;
}
function updateTimer() {
if(m == 0, ms == 0, s == inputVal){
$('#ado').get(0).play();
pause();
}
}
</script>
Thanks again.
First you need inputVal globally as #Denhell mentioned.
var inputVal = Number.POSITIVE_INFINITY;
function getVal(){
inputVal = document.getElementById('inputVal').value;
}
Second your function updateTimer needs a comparison between your inputVal and the actual time of the timer. For playing the sound I transferred your jQuery-code to vanilla JS.
function updateTimer() {
if(getTimer() == inputVal){
document.getElementById('ado').play();
pause();
}
}
In the function run the call of the updateTimer has to be executed at the end because otherwise the value for the comparison doesn't function right at the beginning of a new second or minute (e.g. 00:13:00).
function run(){
stopwatchEL.textContent = getTimer();
ms++;
if(ms == 100){
ms = 0;
s++;
}
if(s == 60){
s = 0;
m++;
}
updateTimer();
}
The only thing is, that the timer stops right but do not update the last ms. For this you could look yourself. For my solution it is necessary that the manually set time is at the format mm:ss:ms with all three values as a 2-digit value like 01:17:09
You can try it here: https://jsfiddle.net/8w67uy5a/5/
You are declaring a variable inputVal inside a getVal function that other functions don't know about it.
Use something like this
var inputVal = Number.POSITIVE_INFINITY;
function getVal(){
inputVal = document.getElementById('inputVal').value;
}
This will fix your problem.
<audio id="ado">
<source src="http://static1.grsites.com/archive/sounds/musical/musical009.mp3" type="audio/mpeg"></source>
</audio>
function getVal() {
const sound = document.getElementById("ado");
sound.play();
var inputVal = document.getElementById("inputVal").value;
}

How to toggle or pause setInterval in javascript

I am learning java Script and i am trying to create clock which should be "when I click the button, the time Should stop changing and the button Should change from “Stop time” to “Start time” & when I click the button again, the time should begin changing and the button should change from “Start time” to “Stop time”. See my codes and tell me which codes or function i need to add and where to add... I am newbie in it so i will appreciate your help..
<!DOCTYPE html>
<html>
<body>
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<button onclick="myStopFunction()">Stop time</button>
</body>
</html>
//---Script Here---
<script>
var myVar = setInterval(function(){ myTimer() }, 1000);
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
function myStopFunction() {
clearInterval(myVar);
}
</script>
Try this one
let currentTime = new Date();
let status = true;
let interval = 1; // in seconds
let dateFormat = { hour: 'numeric', minute:'numeric', second: 'numeric', hour12: true };
let clock = document.querySelector('#demo');
clock.innerHTML = currentTime.toLocaleString('en-US', dateFormat);
let timer = setInterval(
function () {
currentTime.setSeconds(currentTime.getSeconds() + interval);
clock.innerHTML = currentTime.toLocaleString('en-US', dateFormat);
}, interval * 1000
);
let button = document.querySelector('#button');
button.addEventListener('click', onClick);
function onClick() {
if (!status) {
button.innerHTML = 'Stop timer';
timer = setInterval(
function () {
currentTime.setSeconds(currentTime.getSeconds() + interval);
clock.innerHTML = currentTime.toLocaleString('en-US', dateFormat);
}, interval * 1000
);
return;
}
if (status) {
button.innerHTML = 'Start timer';
clearInterval(timer);
}
status = !status;
}
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<button id="button">Stop time</button>
You just need a little trick to toggle the function here you are:
var myVar = setInterval(function () {
myTimer()
}, 1000);
var isPaused = false;
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
function toggleFunction() {
if (isPaused) {
myVar = setInterval(function () {
myTimer()
}, 1000);
isPaused = false;
} else {
clearInterval(myVar);
isPaused = true;
}
}
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<button onclick="toggleFunction()">Toggle time</button>
let time = document.getElementById("time");
let stopButton = document.getElementById("stop");
let timeCount = 0,
currentTimeout;
function play() {
stopButton.hidden = false;
clearInterval(currentTimeout);
currentTimeout = setInterval(() => {
timeCount++;
const min = String(Math.trunc(timeCount / 60)).padStart(2, 0);
const sec = String(Math.trunc(timeCount % 60)).padStart(2, 0);
time.innerHTML = `${min} : ${sec}`;
}, 1000);
}
function pause() {
clearInterval(currentTimeout);
}
function stop() {
stopButton.hidden = true;
pause();
timeCount = 0;
time.innerHTML = `00 : 00`;
}
<div>
<h1 id="time">00 : 00</h1>
<br />
<div>
<button onclick="play()">play</button>
<button onclick="pause()">pause</button>
<button onclick="stop()" id="stop" hidden>Reset</button>
</div>
</div>

JS - function take a double result

I got problem with this script:
<script>
var start = 400;
var interval = 40;
function counter() {
return start -= interval;
}
var stop = setInterval (
function add() {
if (counter() > 0)
document.getElementById("test").innerHTML = counter();
else
clearInterval(stop);
},1000);
</script>
<button onclick="clearInterval(stop)">stop!</button>
<br/>
<p id="test">On marks! Start!</p>
The script counts down from 400 to 0, with a variable interval = 40. When the script runs it subtracts 80 instead of 40. The result is double and I don't know why.
Can you help me?
You're calling counter() twice, subtracting 40 each time, call it just once
var start = 400;
var interval = 40;
function counter() {
return start -= interval;
}
var stop = setInterval(function() {
var count = counter();
if (count > 0) {
document.getElementById("test").innerHTML = count;
} else {
clearInterval(stop);
}
}, 1000);

stopwatch in javascript using new Date object

In script below i try to make some kind of stopwatch:
<html>
<head>
<script>
var t; var time; var timetoRun=180000;// 3 min
function Timer()
{
stoper = (this.startTime+ this.timetoRun)-new Date().getTime();
x = parseInt(stoper / 1000);
s = x % 60;
x = parseInt(x/60);
m = x % 60;
if (s<10) s='0'+ s;document.getElementById('txt').innerHTML=m+':'+s;
this.t=setTimeout(function(){Timer()},500);
}
function myStopFunction(){clearTimeout(t);}
function init(){this.startTime = new Date().getTime();}
</script>
</head>
<body onload="init()">
<div id="txt"></div>
<button onclick="myStopFunction()">Stop time</button>
<button onclick="Timer()">Start time</button>
</body>
</html>
The problem is : when i stop time at 2:28 and start it again after 5 sec. value jump at once to 2:23 . What i want to achieve is: stop time at (for example) 2:31 and run it again from 2:31.
Thanks in advance.
You could simplify a lot your code so to avoid the use of a Date object.
Furthermore you have forgot some var keyword and a condition to stop your timer when the time has run out. I've also inserted a resetTimer method so if you need to restart the timer twice or more, it will be set to 180 seconds again
Example codepen : http://codepen.io/anon/pen/Duier
Code
var
// seconds
timetoRun,
// cache a reference to the DOM element in which you update the timer
timeElement,
// your interval
intv;
function Timer() {
var ss = timetoRun % 60;
var mm = (timetoRun / 60) | 0; // Math.floor
if (ss < 10) ss = '0' + ss;
timeElement.innerHTML = [mm,ss].join(":");
if (timetoRun-- > 0) {
intv = setTimeout(Timer, 1000);
}
else {
myStopFunction();
resetTimer();
}
};
function myStopFunction() { clearInterval(intv); };
function resetTimer() {
timetoRun = 180 //second;
};
function init() {
resetTimer();
timeElement = document.getElementById('txt');
};
I think this is the solution you are looking for
<html>
<head>
<script>
var t;
var time;
var timetoRun=180000;// 3 min
var lastTime = -1;
function StartTimer() {
this.startTime = new Date().getTime();
this.lastTime = lastTime < 0 ? this.timetoRun : this.lastTime;
this.timetoRun = this.lastTime;
Timer();
};
function Timer() {
var difference = (this.startTime - new Date().getTime());
console.log(difference / 1000);
this.lastTime = this.timetoRun + difference;
x = parseInt(this.lastTime / 1000);
s = x % 60;
x = parseInt(x/60);
m = x % 60;
if (s<10) s='0'+ s;
document.getElementById('txt').innerHTML=m+':'+s;
this.t=setTimeout(function(){
Timer();
},500);
}
function myStopFunction() {
clearTimeout(t);
};
</script>
</head>
<body>
<div id="txt"></div>
<button onclick="myStopFunction()">Stop time</button>
<button onclick="StartTimer()">Start time</button>
</body>
</html>
or you can try it here
http://plnkr.co/edit/ySOGRCvnPILNTinCriCL?p=preview
I think you have really over complicated things here the simpler way would be to do something like this http://jsfiddle.net/4Ey9Z/2/
var timetoRun=180000; var timer, elem = document.getElementById('txt');
function startTime(){
timer= setInterval(function(){CountDown()},1000);
}
function stopTime(){
clearInterval(timer);
}
function CountDown(){
var seconds = parseInt((timetoRun/1000)%60,0)
, minutes = parseInt((timetoRun/(1000*60))%60,0);
timetoRun = timetoRun - 1000;
elem.innerHTML=minutes+':'+seconds;
if((seconds===0)&&(minutes ===0)){
stopTime();
}
}

Categories

Resources