I have this code for a timer, i am trying to get it to stop at 0:0 but it keeps going into negative numbers. any ideas to fix this would be a help.
<html>
<head>
<script>
function startTimer(m,s)
{
document.getElementById('timer').innerHTML= m+":"+s;
if (s==0)
{
if (m == 0)
{
clearTimeout(t);
}
else if (m != 0)
{
m = m-1;
s = 60;
}
}
s = s-1;
t=setTimeout(function(){startTimer(m,s)},1000);
}
</script>
</head>
<body>
<button onClick = "startTimer(0,5)">Start</button>
<p id = "timer">00:00</p>
</body>
</html>
You're always firing a new timer at the end of startTimer, even when you reach zero. The quick fix is to add a return; after instead of clearTimeout(t);.
you can make the timeout function external and call it when time is more than 0:0 like this:
function startTimer(m,s)
{
document.getElementById('timer').innerHTML= m+":"+s;
if (s==0)
{
if (m == 0)
{
alert('done');
}
else if (m != 0)
{
m = m-1;
s = 60;
t();
}
}
s = s-1;
t();
function t(){setTimeout(function(){startTimer(m,s)},1000)};
}
or shorthand version:
function startTimer(m,s)
{
document.getElementById('timer').innerHTML= m+":"+s;
(s == 0) ? (m == 0 ? alert('done') : (m--, s = 60, t())) : (s--, t());
function t(){ setTimeout(function(){startTimer(m,s)},1000)};
}
jsfiddle
Just a comment—the function can be a lot slimmer:
function pad(n) {
return (n<10? '0':'') + n;
}
function startTimer(m,s) {
document.getElementById('timer').innerHTML = pad(m) + ":" + pad(s);
s -= s? 1 : m-- && -59;
if (m != -1)
setTimeout(function(){startTimer(m,s)},1000);
}
It will slowly drift as setTimeout doesn't run at exactly the time specified so it should use a date object to adjust the lag to the next full second.
its an old code that ive written:
function CountDown(TimeToCount){
if(First)
{
var startDatum=new Date();
First = false;
date.a = startDatum;
bye = TimeToCount-200;
}
if(bye > 0 && CDown){
var zielDatum=new Date();
bye =Math.abs(Math.floor(( ((zielDatum-(TimeToCount-200)-date.a)/1000) - 0.1)*10)/10);
if ( bye * 10 % 10 ==0)
$(".CountDown").html(bye+".0");
else
$(".CountDown").html(bye);
setTimeout(function(){CountDown(TimeToCount)},20);
}
else
{ $(".CountDown").html("0.0");
}
}`
Related
I made a little typing game that reveals some random text and you have to type the same in, so that you can test your typing speed. the users has the ability to play again and again, the issue is that when the user types play again, the stopwatch does not begin as it did the first time.
Can anyone help me with making the stopwatch restart everytime the user clicks on the play again button?
[ full code is here] (https://jsfiddle.net/kisho/ncbxd9o4/#&togetherjs=qD5bT8vLiw)
js portion-
const textDisplay = document.querySelector('#text-display');
const input = document.querySelector('#input');
const btn = document.querySelector('#btn');
const textBox = document.querySelector('#text-box');
const countdown = document.querySelector('#countdown');
const stopwatch = document.querySelector('#stopwatch');
const successMessege = document.querySelector('#success-messege');
const stopwatchTime = document.querySelector('#stopwatch-time');
btn.addEventListener('click', runGame);
function runGame() {
if ((btn.innerText = 'Play again')) {
playAgain();
fetchQuote();
countownTimer();
confirmQuote();
} else {
fetchQuote();
countownTimer();
confirmQuote();
}
}
function fetchQuote() {
fetch('https://api.quotable.io/random')
.then((res) => {
return res.json();
})
.then((data) => {
textDisplay.innerText = data.content;
});
}
function countownTimer() {
if (timer !== undefined) {
clearInterval(timer);
}
var timeleft = 2;
var downloadTimer = setInterval(function() {
if (timeleft <= 0) {
clearInterval(downloadTimer);
document.getElementById('countdown').innerHTML = 'Start Typing!';
input.classList.remove('displayNone');
runningStopwatch.classList.remove('displayNone');
begin();
} else {
document.getElementById('countdown').innerHTML = timeleft + ' seconds remaining';
}
timeleft -= 1;
}, 1000);
}
function confirmQuote() {
if ((countdown.innerHTML = 'Start typing!')) {
input.addEventListener('keyup', function(event) {
if (event.keyCode === 13) {
if (textDisplay.innerText === input.value) {
btn.innerText = 'Play again';
// textBox.classList.add('displayNone');
hold();
} else successMessege.innerText = 'Missed something there, try again!!';
}
});
}
}
function playAgain() {
textBox.classList.remove('displayNone');
input.classList.add('displayNone');
input;
input.value = '';
successMessege.innerText = '';
}
let ms = 0,
s = 0,
m = 0;
let timer;
let runningStopwatch = document.querySelector('.running-stopwatch');
function begin() {
timer = setInterval(run, 10);
}
function run() {
runningStopwatch.textContent =
(m < 10 ? '0' + m : m) + ': ' + (s < 10 ? '0' + s : s) + ': ' + (ms < 10 ? '0' + ms : ms);
ms++;
if (ms == 100) {
ms = 0;
s++;
}
if (s == 60) {
s = 0;
m++;
}
}
function hold() {
clearInterval(timer);
successMessege.innerText = `Nice job! You just typed in x seconds!`;
}
function stop() {
(ms = 0), (s = 0), (m = 0);
runningStopwatch.textContent =
(m < 10 ? '0' + m : m) + ': ' + (s < 10 ? '0' + s : s) + ': ' + (ms < 10 ? '0' + ms : ms);
}
You are not handling the clearInterval correctly.
You are clearing the interval only if one ends the game successfully.
My solution would be:
When calling the countownTimer() function, the first thing you should do, is to check if the interval timer is still running.
function countownTimer() {
if (timer !== undefined) {
clearInterval(timer);
}
// [...]
}
The next thing would be, to start the interval every time begin() gets called.
function begin() {
timer = setInterval(run, 10);
}
i am just trying to do time counter. when 30 seconds will be over the alert box from another function will popup. i made the code and it's worked for some times too. but now it's not calling the function it only call when i refresh the page.
<html>
<head>
<title>Timer</title>
</head>
<body>
<form name="counter"><input type="text" size="8" name="d2"></form>
<script>
var milisec = 0
var seconds = localStorage.seconds || 30;
document.counter.d2.value = seconds;
function display() {
if (milisec <= 0) {
milisec = 9
seconds -= 1
}
if (seconds <= -1) {
milisec = 0
seconds += 1
}
else{
milisec -= 1
}
if(seconds <= 0 && milisec < 1)
{
console.log("done");
localStorage.clear();
anotherFunction();
}
else
{
localStorage.seconds = seconds;
}
document.counter.d2.value = seconds + "." + milisec;
if (seconds > 0 || (seconds == 0 && milisec > 0)) {
setTimeout(display, 100);
}
else
{
}
}
display();
function anotherFunction()
{
alert("reached");
}
</script>
</body>
</html>
`
here is the code.
I think this ones helps you.
if(seconds<=0)
{
throw '';
}
put this function before the function.
Please help me with my code.My problem is when the timer is finished, it shows -1:60 instead of showing 0:00.I tried different ways of else statement,but in vain. When I change the condition in if statement to x>0,the timer doesn't go down from 0:60. Any help will be appreciated. I tried different else, if else statements,nothing helps.
Thank you in advance.
<h1 id='session' onClick='general()'>2</h1>
JS:
var seconds=60;
var x=document.getElementById('session').innerHTML-1;
var t;
function timer(){
if(x>=0){
seconds--;
if(seconds<10){
seconds='0'+seconds;
};
if(seconds==0){
x--;
seconds=60;
}
}
document.getElementById('session').innerHTML=x+':'+seconds;
}
function stoptimer(){
clearInterval(t);
}
var on=true;
function general(){
if(on){
on=false;
t = setInterval(timer,200);
}else{
on=true;
stoptimer();
}
}
The problem is all because of the timer funtion, so I've made a few changes to your function, and rewritten it. I ran it in the jsfiddle and it's working.
function timer(){
if(x>=0 && flag==false){
seconds--;
if(seconds<10){
seconds='0'+seconds;
};
if(seconds==0){
x--;
seconds=60;
}
}
if (x == -1){
flag=true;
x = 0;
seconds = '00';
}
document.getElementById('session').innerHTML=x+':'+seconds;
}
Make sure you take a global variable var flag=false; in order for this function properly.
Here is the link for the jsfiddle I created: https://jsfiddle.net/35w4nkzm/1/
I hope that helped.
I created a fiddle for you, it countdowns the timer from 60 seconds to 00.
Fiddle : https://jsfiddle.net/njw73naj/
HTML
<h1>
<span id="min">0</span>
:
<span id="sec">00</span>
</h1>
JS
var seconds = 60,
secondDom = document.getElementById("sec");
secondDom.innerHTML = seconds;
var countdown = function(){
seconds--;
if(seconds < 0){
clearInterval(timer);
}else{
secondDom.innerHTML = (seconds < 10 ? "0" + seconds : seconds);
}
}
var timer = setInterval(countdown,1000);
Hope this helps. :)
I've removed certain unnecessary things from your code. though,
you should know it's not really 2 minutes. my "setInterval" is based
on your original setInterval.
HTML:
<h1 id='session' onclick='general()'>1</h1>
JS:
<script>
var seconds = 60;
var x = document.getElementById('session').innerHTML;
var t;
function timer(){
if (x === 0 && seconds === 0)
{
stoptimer(t);
}
else if(seconds === 0){
seconds = 60;
x--;
}
else{
seconds--;
}
document.getElementById('session').innerHTML = x + ':' + seconds;
}
function stoptimer(){
clearInterval(t);
}
var on = true;
function general(){
if(on){
on=false;
t = setInterval(timer,200);
}else{
on=true;
stoptimer();
}
}
</script>
function testworking(n){
if(n == 1)
testuser();
else
testconfig();
}
setInterval(function(){testworking(n)}, 1000);
How do I make that function testuser(); could not start earlier than 10 seconds after the previous launch?
P.S.:
an approximate algorithm:
if(n == 1){
if (first run function `testuser()` ||
time after previous run `testuser();` == 10 seound){
testuser();
}
}
Set a flag using a timer:
var is_waiting = false;
function testuser() {
if (!is_waiting) {
//do your stuff here
} else {
alert('You must wait ten seconds before doing this again');
}
is_waiting = true;
setTimeout(function() {is_waiting = false}, 10000);
}
You can do it like this
var i = 0;
function testworking(i){
if(i < 10) {
console.log(i);
} else {
console.log('Here is 10 second');
}
}
setInterval(function(){
i = (i == 10) ? 0 : i;
i++;
testworking(i);
}, 1000);
It's not entirely clear what you're looking for, but here's something that might give you an idea.
var n = 1;
var testUserInterval;
function testworking(n) {
if (n == 1)
testuser();
else
testconfig();
}
function testuser() {
var cnt = 0;
if (testUserInterval == null) {
testUserInterval = setInterval(function() {
document.getElementById("testusercnt").innerHTML = cnt;
cnt += 1;
if (cnt == 10) {
clearInterval(testUserInterval);
testUserInterval = null;
//DO SOMETHING ???
testuser();
}
}, 1000);
}
}
function testconfig() {
document.getElementById("testconfig").innerHTML = n;
}
setInterval(function() {
testworking(n++)
}, 1000);
testuser cnt:<span id="testusercnt"> </span>
<br/>testconfig n: <span id="testconfig"> </span>
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