Countdown timer not stopping at 0 - javascript

For some reason, my timer does not stop when the time reaches 0. JSFiddle. Here is the constructor for the countdown timer I made:
var Timer = function(opts) {
var self = this;
self.opts = opts || {};
self.element = opts.element || null;
self.minutes = opts.minutes || 0;
self.seconds = opts.seconds || 30;
self.start = function() {
self.interval = setInterval(countDown, 1000);
};
self.stop = function() {
clearInterval(self.interval);
};
function countDown() {
if (self.minutes == 0 && self.seconds == 0) {
self.stop();
}
self.seconds--;
if (self.seconds <= 0) {
self.seconds = 59;
self.minutes--;
}
if (self.seconds <= 9) { self.seconds = '0' + self.seconds; }
self.element.textContent = self.minutes + ' : ' + self.seconds;
}
};
and here is my usage:
HTML:
<div id="timer"></div>
JavaScript:
var myTimer = new Timer({
minutes: 0,
seconds: 10,
element: document.querySelector('#timer')
});
myTimer.start();

Change your countdown function to
function countDown() {
self.seconds--; //Changed Line
if (self.minutes == 0 && self.seconds == 0) {
self.stop();
}
if (self.seconds < 0) { //Changed Condition. Not include 0
self.seconds = 59;
self.minutes--;
}
if (self.seconds <= 9) { self.seconds = '0' + self.seconds; }
self.element.textContent = self.minutes + ' : ' + self.seconds;
}
http://jsfiddle.net/8d5LLeoa/3/

You just need to rearrange your countdown function a bit. It will never be zero when it hits your code that checks for a zero value. The code below works.
function countDown() {
self.seconds--;
self.element.textContent = self.minutes + ' : ' + self.seconds;
if (self.minutes === 0 && self.seconds === 0) {
self.stop();
return;
}
if (self.seconds <= 0) {
self.seconds = 59;
self.minutes--;
}
if (self.seconds <= 9) { self.seconds = '0' + self.seconds; }
}
};

Related

JQuery - How to update variable after call function?

I have a timer function, I want to change the value of my variable after the timer reaches 0?
function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
var counter = document.getElementById("timer");
current_minutes = mins - 1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if (parseInt(current_minutes) === 0 && parseInt(seconds) === 00) {
sendAgain.show();
finalMin = parseInt(current_minutes);
finalSec = parseInt(seconds);
}
if (seconds > 0) {
timeoutHandle = setTimeout(tick, 1000);
} else {
if (mins > 1) {
// countdown(mins-1); never reach “00″ issue solved:Contributed by Victor Streithorst
setTimeout(function () { countdown(mins - 1); }, 1000);
}
}
}
tick();
}
variables :
let finalMin = null;
var finalSec = null;
I want the variables to be set after the following code is executed?
if (parseInt(current_minutes) === 0 && parseInt(seconds) === 00) {
sendAgain.show();
finalMin = parseInt(current_minutes);
finalSec = parseInt(seconds);
}
countdown(2);
console.log(finalMin); ===== show "0"

Javascript setInterval flickering

I'm trying to create a chess clock using JavaScript. I've settle almost all of the issues with the clock's functionality except for this one. I'm using setInterval to essentially create the "countdown" effect on each player's clock. However, when it is triggered with the method I'm currently using the clock flickers. From my understanding/research, this is likely because there are overlapping 'intervals' that cause the code to try to display multiple intervals at the same time. Essentially the clock buttons (stopclock and stopclock2) when clicked call the functions on the bottom of my code. Could anyone provide some input on my code (below) and why this might be occurring?
clear1mils = "";
clear2mils = "";
//Clock Functions
function countdownmils2() {
document.getElementById("milsvalue2").innerHTML = --mil2;
if (mil2 == 0) {
mil2 = mil2 + 59;
if (sec2 == 0) {
if (min2 == 0) {
clearInterval(clear2mils);
document.getElementById("milsvalue2").innerHTML = "00";
}else if (min2 !== 0) {
sec2 = 60;
document.getElementById("minutesvalue2").innerHTML = --min2;
document.getElementById("secondsvalue2").innerHTML = --sec2;
}
}else if (sec2 !== 0) {
document.getElementById("secondsvalue2").innerHTML = --sec2;
if (sec2 <= 10) {
document.getElementById("secondsvalue2").innerHTML = "0" + sec2;
}
}
}else if (mil2 <= 10) {
document.getElementById("milsvalue2").innerHTML = "0" + mil2;
}
}
function countdownmils() {
document.getElementById("milsvalue").innerHTML = --mil;
if (mil == 0) {
mil = mil + 59;
if (sec == 0) {
if (min == 0) {
clearInterval(clear1mils);
document.getElementById("milsvalue").innerHTML = "00";
}else if (min !== 0) {
sec = 60;
document.getElementById("minutesvalue").innerHTML = --min;
document.getElementById("secondsvalue").innerHTML = --sec;
}
}else if (sec !== 0) {
document.getElementById("secondsvalue").innerHTML = --sec;
if (sec <= 10) {
document.getElementById("secondsvalue").innerHTML = "0" + sec;
}
}
}else if (mil <= 10) {
document.getElementById("milsvalue").innerHTML = "0" + mil;
}
}
//Clock 1
document.querySelector("#stopclock").addEventListener("click", () => {
clear2mils = setInterval(countdownmils2, 10);
clearInterval(clear1mils);
document.getElementById("stopclock").innerHTML = "DOWN";
document.getElementById("stopclock2").innerHTML = "UP";
document.getElementById("stopclock").setAttribute("disabled", "true");
document.getElementById("stopclock2").removeAttribute("disabled", "true");
});
//Clock 2
document.querySelector("#stopclock2").addEventListener("click", () => {
clear1mils = setInterval(countdownmils, 10);
clearInterval(clear2mils);
document.getElementById("stopclock2").innerHTML = "DOWN";
document.getElementById("stopclock").innerHTML = "UP";
document.getElementById("stopclock2").setAttribute("disabled", "true");
document.getElementById("stopclock").removeAttribute("disabled", "true");
});

Having issue resetting JS stopwatch

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

JQuery / JavaScript Keyboard event

I have a typing speed test with a textarea and I have I paragraph split into spans. Every time the user hits space, it highlights the next span. Then I split the textarea val() and compare the two at the end. I have everything working except I cannot get the enter key to do what I want it to do. I need it to act like the space bar(in the background) and act as the enter key on screen.
$(function() {
//APPEARANCE
$('#error').hide();
$('#oldTextOne').hide();
$('#oldTextTwo').hide();
$('#oldTextThree').hide();
$('#oldTextFour').hide();
$('#oldTextFive').hide();
$('.linkBox').hover(function() {
$(this).removeClass('linkBox').addClass('linkHover');
}, function() {
$(this).removeClass('linkHover').addClass('linkBox');
});
//FUNCTIONALITY VARIABLES
var min = '5';
var sec = '00';
var realSec = 0;
var errorTest = "hasn't started yet";
var oldTextVal;
var para;
// PICK A RANDOM PARAGRAPH
function pickRandom() {
var date = new Date();
date = date.getTime();
date += '';
var dateSplit = date.split('');
var temp = dateSplit.length - 1;
var picker = dateSplit[temp];
if (picker === '0' || picker === '1') {
para = $('#oldTextOne').text();
}
else if (picker === '2' || picker === '3') {
para = $('#oldTextTwo').text();
}
else if (picker === '4' || picker === '5') {
para = $('#oldTextThree').text();
}
else if (picker === '6' || picker === '7') {
para = $('#oldTextFour').text();
}
else {
para = $('#oldTextFive').text();
}
var splitPara = para.split(' ');
for (i in splitPara) {
$('#oldTextBox').append('<span id="pw' + i + '">' + splitPara[i] + '</span> ');
}
}
pickRandom();
//FUNCTION FOR TIMER
//APPEARANCE
function show() {
$('#timer').text(min + ' : ' + sec);
}
show();
//COUNT-DOWN
var count = function() {
sec = +sec - 1;
sec += '';
realSec++;
if (+sec === -1) {
sec = '59';
min -= 1;
min += '';
}
if (sec.length === 1) {
sec = '0' + sec;
}
show();
if (sec === '00' && min === '0') {
clearInterval(run);
checkIt();
}
};
// TYPE THE TEXT INTO #TYPEDTEXTBOX
$('#pw0').addClass('green');
var lastLetter;
$('#typedTextBox').focus().keypress(function() {
if (errorTest === "hasn't started yet") {
errorTest = 'running';
run = setInterval(count, 1000);
}
//STOP ERRORS FROM PEOPLE HITTING SPACE BAR TWICE IN A ROW !!NOT WORKING IN IE8
var thisLetter = event.which;
if (lastLetter === 32 && event.which === 32) {
event.preventDefault();
}
lastLetter = thisLetter;
}).keyup(function() {
//STOP ERRORS FROM BACKSPACE NOT REGISTERING WITH KEYPRESS FUNCTION
if (event.which === 8) {
lastLetter = 8;
}
if (event.which === 13) {
?????????????????????????????????????????????
}
//SPLIT THE TYPED WORDS INTO AN ARRAY TO MATCH THE OLD TXT SPANS (TO HIGHLIGHT THE CURRENT WORD IN OLDTXT)
var typedWords = $(this).val().split(' ');
var temp = typedWords.length - 1;
var oldTemp = temp - 1;
var stopErrors = temp + 1;
$('span:nth(' + temp + ')').addClass('green');
$('span:nth(' + oldTemp + ')').removeClass('green');
$('span:nth(' + stopErrors + ')').removeClass('green');
//SCROLL
if (typedWords.length < 50) {
return;
}
else if (typedWords.length > 50 && typedWords.length < 100) {
$('#oldTextBox').scrollTop(30);
}
else if (typedWords.length > 100 && typedWords.length < 150) {
$('#oldTextBox').scrollTop(60);
}
else if (typedWords.length > 150 && typedWords.length < 200) {
$('#oldTextBox').scrollTop(90);
}
else if (typedWords.length > 200) {
$('#oldTextBox').scrollTop(120);
}
//KEEP FOCUS IN THE TYPING AREA
}).blur(function() {
if (errorTest !== 'done') {
$(this).focus();
}
});
//COMPARE
//MAKE AN ARRAY OF THE OLDTEXT
var oldWords = para.split(' ');
//FUNCTION TO DISPLAY RESULTS
var checkIt = function() {
errorTest = 'done';
var correct = 0;
var typed = $('#typedTextBox').val();
var typedWords = typed.split(' ');
$('#typedTextBox').blur();
for (i = 0; i < typedWords.length; i++) {
if (typedWords[i] === oldWords[i]) {
correct += 1;
}
}
var errors = typedWords.length - correct;
var epm = (errors / realSec) * 60;
var wpm = Math.round(( ($('#typedTextBox').val().length / 5 ) / realSec ) * 60);
var realWpm = Math.round(wpm - epm);
//SHOW RESULTS
$('#oldTextBox').html('<br><span id="finalOne">WPM : <strong>' + realWpm + ' </strong></span><span class="small">(error adjusted)</span><br><br><span id="finalTwo">You made ' + errors + ' errors </span><br><span id="finalThree">Total character count of ' + $('#typedTextBox').val().length + '</span><br><span id="finalFour">Gross WPM : ' + wpm + '</span>');
};
//STOP BUTTON APPEARANCE AND FUNCTIONALITY
$('#stop').mouseover(function() {
$(this).addClass('stopHover');
}).mouseout(function() {
$(this).removeClass('stopHover');
}).click(function() {
if (errorTest === 'running') {
checkIt();
clearInterval(run);
errorTest = 'done';
}
});
});
try this:
//ENTER KEY
if (event.which === 13) {
//event.stopPropagation(); or
event.preventDefault();
//simulate spacebar
$(window).trigger({type: 'keypress', which: 32, keyCode: 32});
}
#james - Thanks for the help. I found a better way of thinking about the problem. Instead of changing the enter key action, I changed the split function to var typedWords = typed.split(/[ \r\n]+/);

`if (Date >= Date1 && <= Date2 ){do this}` dosn´t work

The code changes the new Date() to DayHourMinute
e.g. monday9AM45minutes to 010945
What I use is 010945 and my code specifies
if the var is between >=010921 && <=011010
change the background to green else nothing
But nothing happens and if I use alert(Time) it gives the message 010945.
How can if fix this?
Code:
function one() {
now = new Date();
hour = "" + now.getHours();
if (hour.length == 1) {
hour = "0" + hour;
}
minute = "" + now.getMinutes();
if (minute.length == 1) {
minute = "0" + minute;
}
day = "" + now.getDay();
if (day.length == 1) {
day = "0" + day;
}
var Time = day + '' + hour + '' + minute;
if (Time >= 010835 && Time <= 010920) {
document.getElementById('Man1').style.background = 'green';
} else {
document.getElementById('Man1').style.background = '';
}
if (Time >= 010921 && Time <= 011010) {
document.getElementById('Man2').style.background = 'green';
} else {
document.getElementById('Man2').style.background = '';
}
if (Time >= 011011 && Time <= 011105) {
document.getElementById('Man3').style.background = 'green';
} else {
document.getElementById('Man3').style.background = '';
}
if (Time >= 011106 && Time <= 011155) {
document.getElementById('Man4').style.background = 'green';
} else {
document.getElementById('Man4').style.background = '';
}
if (Time >= 011156 && Time <= 011239) {
document.getElementById('Man5').style.background = 'green';
} else {
document.getElementById('Man5').style.background = '';
}
if (Time >= 011240 && Time <= 011325) {
document.getElementById('Man6').style.background = 'green';
} else {
document.getElementById('Man6').style.background = '';
}
if (Time >= 011326 && Time <= 011415) {
document.getElementById('Man7').style.background = 'green';
} else {
document.getElementById('Man7').style.background = '';
}
if (Time >= 011416 && Time <= 011505) {
document.getElementById('Man8').style.background = 'green';
} else {
document.getElementById('Man8').style.background = '';
}
if (Time >= 011506 && Time <= 011555) {
document.getElementById('Man9').style.background = 'green';
} else {
document.getElementById('Man9').style.background = '';
}
}
setInterval(one, 1000);
Fiddle
Time is a string, and you are comparing to an int. Put the values in quotes:
if ( Time>='020000' && Time<='030000' ){

Categories