Stop jQuery timer at 0 using clearInterval - javascript

I'm having issues using clearInterval to stop my simple count timer once it is equal to 0. Essentially, timer goes past 0 into negative values instead of stopping at 0. I am creating a basic quiz that ideally will alert the user of the correct answers once the timer reaches and stops at 0.
Below is current code:
var count = 10;
var gameTime;
gameTime = setInterval("counter()", 1000);
function convertSeconds(s){
var min = Math.floor(s / 60);
var sec = s % 60;
return min + ":" + sec;
}
function counter(){
count--;
$("#timer").text(convertSeconds(count));
}
if (count === 0) {
clearInterval("#timer");
} else {
//Do nothing
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Trivia</title>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
</head>
<body>
<div id ="timer">10</div>
</body>

Just move your if check into the counter function and clear the gameTime variable.
setInterval runs the provided function at the given interval so anything you want to run or check on that interval must happen in the provided function.
var count = 10;
var gameTime;
gameTime = setInterval("counter()", 1000);
function convertSeconds(s){
var min = Math.floor(s / 60);
var sec = s % 60;
return min + ":" + sec;
}
function counter(){
count--;
$("#timer").text(convertSeconds(count));
if (count === 0) {
clearInterval(gameTime);
} else {
//Do nothing
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Trivia</title>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
</head>
<body>
<div id ="timer">10</div>
</body>

Related

Stopwatch - keeping the elapsed time at zero before the start timer onclick handler is clicked

Stopwatch - keeping the elapsed time at zero before the start timer onclick handler is clicked
Hi, I have been working on a Javascript stopwatch for an interview test. I have an issue where the timer starts automatically when the browser loads. I have tried editing the add() function's 'if' statement but not having any joy with it. Can anyone help me?
var h1 = document.getElementsByTagName('h1')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
milli = 0, seconds = 0, minutes = 0, hours = 0,
t;
function add() {
milli += 10;
if (milli >= 1000) {
milli = 0;
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) + "." + (milli > 90 ? milli : "0" + milli);
timer();
}
function timer() {
t = setTimeout(add, 10);
}
timer();
/* Start button */
start.onclick = timer;
/* Stop button */
stop.onclick = function() {
clearTimeout(t);
}
/* Clear button */
clear.onclick = function() {
h1.textContent = "00:00:00:00";
milli = 0; seconds = 0; minutes = 0; hours = 0;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test Stopwatch</title>
<link rel="stylesheet" href="assets/css/styles.css">
</head>
<body>
<section>
<h1>
<time>00:00:000:00</time>
</h1>
<button id="start">START</button>
<button id="stop">STOP</button>
<button id="clear">CLEAR</button>
</section>
<script src="assets/js/script.js"></script>
</body>
</html>
You have a timer() call on the root of the javascript file scope so it is invoked automatically.
function timer() {
t = setTimeout(add, 10);
}
timer(); // This starts it automatically. remove it.
correct:
function timer() {
t = setTimeout(add, 10);
}

Problem with the countdown timer JS - IF Condition

I'm new to JavaScript and this website.
I have the following code for an event timer countdown:
https://codepen.io/iraffleslowd/pen/povGNdo
My problem really is with an if condition.
setInterval(function () {
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
Because my event does not expire at the end of the countdown, it ends approximately one hour after starting.
So can someone help me add another condition so that in the interval of that time instead of showing me Expired, it shows Live or something similar?
Thank you so much!
You want to manage 3 different states...
Counting down until LIVE
LIVE
EXPIRED
(() => {
const intervalId = setInterval(() => {
// update countdown timer
if (distance < -(ELAPSED_GAMETIME_IN_MS)) {
// set EXPIRED
clearInterval(intervalId);
}
else if (distance < 0) {
// set LIVE
}
}, 1000);
})();
EDIT
Working example
This example utilizes moment because it's a great utility that provides all necessary math and formatting for dates and is perfect for this scenario.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<div id="countdown"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
<script>
(() => {
const countdownEl = document.getElementById("countdown");
const START_DATE = moment("2020-01-22");
const ELAPSED_GAMETIME_IN_MS = 1000 * 60 * 60 * 2; // 2 hours in milliseconds
const intervalId = setInterval(() => {
const TIME_FROM_START = START_DATE.diff(moment());
countdownEl.innerHTML = START_DATE.fromNow(); // This could be modified to show different levels of granularity...
if (TIME_FROM_START < -ELAPSED_GAMETIME_IN_MS) {
countdownEl.innerHTML = "EXPIRED";
clearInterval(intervalId);
} else if (TIME_FROM_START < 0) {
countdownEl.innerHTML = "LIVE";
}
}, 1000);
})();
</script>
</body>
</html>
It looks like an else-statement can resolve your issue.
Try
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
else {
document.getElementById("demo").innerHTML = "LIVE";
}

How to count up sec, min, hours and days in a proper way?

I would like to write a counter, that counts me every sec, min, hour and day. It shouldn't start from 0 but from 2 min. For now I have the following code, but it doesn't seems to be right. I'm a beginner and trying to understand JS. Thanks in advance for your help and pations!
<!doctype html>
<html>
<head>
<title>Counter</title>
<script>
start=new Date().getTime()-120000;
function updateCounter() {
var dif=new Date().getTime()-start;
setTimeout(updateCounter, 1000-(dif%1000));
var sec=Math.floor(dif/1000);
var min=Math.floor(sec/60);
var hou=Math.floor(min/60);
var day=Math.floor(hou/24);
sec %= 60;
if (sec<10) {
sec="0"+sec;
}
document.getElementById("counter").innerHTML=day+":"+hou+":"+min+":"+sec;
}
</script>
</head>
<body onload="updateCounter();">
<p id="counter"></p>
</body>
</html>
Sorry, didn't know that I can't put code into a reply of a comment. So here is my improved code. The problem is, that I have no idea how I can switch from 24 h to 1 day. Right now it counts 1day24h0m0sec. But it should be 1day0h0m0sec.
<!doctype html>
<html>
<head>
<title>Counter</title>
<script>
var start=new Date().getTime()-86400000;
function updateCounter() {
var dif=new Date().getTime()-start;
setTimeout(updateCounter, 1000-(dif%1000));
var sec=Math.floor(dif/1000);
var min=Math.floor(sec/60);
var hou=Math.floor(min/60);
var day=Math.floor(hou/24);
sec %= 60;
if (sec<10) {
sec="0"+sec;
}
min %= 60;
if (min<10) {
min="0"+min;
}
hou %= 60;
if (hou<10) {
hou="0"+hou;
}
day %= 24;
if (day<10) {
day="0"+day;
}
document.getElementById("counter").innerHTML=day+":"+hou+":"+min+":"+sec;
}
</script>
</head>
<body onload="updateCounter();">
<p id="counter"></p>
</body>
</html>

Javascript setTimeout function with JQuery

I'm new to JQuery and Javascript, I try to write a small setTimeout function but it seems not to work. Below is my code, can some one help out by pointing out what is wrong here.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>countdown</title>
<script type="text/javascript" src="/jquery-2.1.4.js"></script>
<script>
$("#submit").click(function(){
var timeVal = $("#input").val();
var mainTimeVal = timeVal.split(":");
var minute = parseInt(mainTimeVal[0]);
var second = parseInt(mainTimeVal[1]);
//console.log( second);
setTimeout(function () {
if (minute == 0 && second == 0) {
alert("no time left");
}
else if (second !== 0) {
second--;
}
else {
minute--;
second = 60;
}
second--;
}, 1000);
});
</script>
</head>
<body>
<input type="text" id="input" value="25:23"/><br>
<button type="button" id="submit" value="send"></button>
</body>
</html>
Your code executes on .click on the submit button - which means it only executes when you click the button. Also using setTimeout you are only running it once, and by the inner logic of the function it seems you want it to be ongoing. Substitute setTimeout to setInterval to keep it running.
`$("#submit").click(function(){
var timeVal = $("#input").val();
var mainTimeVal = timeVal.split(":");
var minute = parseInt(mainTimeVal[0]);
var second = parseInt(mainTimeVal[1]);
//console.log( second);
setInterval(function () {
if (minute == 0 && second == 0) {
alert("no time left");
}
else if (second !== 0) {
second--;
}
else {
minute--;
second = 60;
}
$('#input').val(minute + ':' + second);
}, 1000);
});`
have to recursive to make call and call again....
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>countdown</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<input type="text" id="input" value="25:23"/><br>
<input type="button" id="submit" value="send"></input>
<script>
$("#submit").click(function(){
var timeVal = $("#input").val();
var mainTimeVal = timeVal.split(":");
var minute = parseInt(mainTimeVal[0]);
var second = parseInt(mainTimeVal[1]);
//console.log( second);
setTimeout(function () {
rece();
function rece(){
if (minute == 0 && second == 0) {
alert("no time left");
console.log('no time left')
}
else if (second !== 0) {
second--;
console.log('second');
rece();
}
else {
minute--;
second = 60;
console.log('minute');
rece();
}
second--;
}
}, 100);
});
</script>
</body>
</html>
I've modified your code slightly and created a fiddle: JsFiddle
$("#submit").click(function(){
var timeVal = $("#input").val();
var mainTimeVal = timeVal.split(":");
var minute = parseInt(mainTimeVal[0]);
var second = parseInt(mainTimeVal[1]);
setTimeout(function () {
if (minute == 0 && second == 0) {
alert("no time left");
}
else if (second !== 0) {
second--;
}
else {
minute--;
second = 60;
}
second--;
$('#input').val(minute + ':' + second);
}, 1000);
});

How can I make animation duration more accurate based on setInterval (js)

I'm writing an animation looks like number is rising in limited time.
use setInternal and clearInterval to implement it.(I don't want to use Jquery)
the interval time is 1 milliSecond. And limit time is 1000 milli seconds. But it is slower than expected. It went almost 10000 milliseconds.What am I doing wrong?
Here's my code.
<html>
<head>
<title>A numeric test</title>
</head>
<body>
<div id="numberScroll"></div>
<script type="text/javascript">
var limitTime = 100; //milliSeconds
var goalNum = 123456; //the final num
var increament = false; //whether the animation is increasing of not.
var textSize = 30; //size of text
var temNum = increament ? (goalNum * 0.8) : (goalNum * 1.2); //start number
temNum = eval(temNum.toFixed(2));
var increamentNum = (goalNum - temNum) / limitTime;
var numberScroll = document.getElementById("numberScroll");
if(numberScroll === null) {
console.log("No Element Found");
}
numberScroll.style.fontSize = textSize;
numberScroll.innerHTML = temNum;
var intervalId = setInterval(function(){
numberScroll.innerHTML = temNum.toFixed(2);
temNum += increamentNum;
if(increament){
if(temNum >= goalNum) {
clearInterval(intervalId);
numberScroll.innerHTML = goalNum;
}
} else {
if(temNum <= goalNum) {
clearInterval(intervalId);
numberScroll.innerHTML = goalNum;
}
}},1);
</script>
</body>
</html>

Categories

Resources