Why can't I see the countdown timer - javascript

I tried to make a countdown timer using setInterval(). I used code made by other people to learn how, but it failed. After searching to find the issue, I was not able to find it.
My code:
<!DOCTYPE html>
<html>
<head>
<title>Count</title>
<script="text/javascript">
var Stime = 10; //Set time(minute)
var Ssecond = Stime * 60;
var countdownID=0;
function inidown(){
countdownID = setInterval("Count()",1000);
}
function Count(){
if(Ssecond>0){
var rM=Ssecond/60;
var rS=Ssecond%60;
document.getElementById("count").innerHTML=rM+":"+rS;
Ssecond--;
}
else{
clearInterval(countdownID);
document.getElementById("out").innerHTML="time out";
}
}
</script>
</head>
<body onload="inidown()">
<div id="count"></div>
<div id="out"></div>
</body>
</html>
I saw that code on http://blog.niklasottosson.com/?p=665
var Stime = 10; //?? ??(?)
var Ssecond = Stime * 60;
var countdownID = 0;
function inidown() {
countdownID = setInterval("Count()", 1000);
}
function Count() {
if (Ssecond > 0) {
var rM = Ssecond / 60;
var rS = Ssecond % 60;
document.getElementById("count").innerHTML = rM + ":" + rS;
Ssecond--;
} else {
clearInterval(countdownID);
DivCount.innerHTML = "Time Out";
document.getElementById("out").innerHTML = "time out";
}
}
No error occurs in that code.

There was a problem with your script tag.
Use Math.floor for your minutes.
Pad the seconds for single digits.
<html>
<head>
<title>Count</title>
<script type="text/javascript">
var Stime = 10; //Set time(minute)
var Ssecond = Stime * 60;
var countdownID = 0;
function inidown() {
countdownID = setInterval("Count()", 1000);
}
function Count() {
if (Ssecond > 0) {
var rM = Math.floor(Ssecond / 60);
var rS = ("0" + (Ssecond % 60)).slice(-2);
document.getElementById("count").innerHTML = rM + ":" + rS;
Ssecond--;
} else {
clearInterval(countdownID);
document.getElementById("count").innerHTML = "";
document.getElementById("out").innerHTML = "Time Out";
}
}
</script>
</head>
<body onload="inidown()">
<div id="count"></div>
<div id="out"></div>
</body>
</html>

<script="text/javascript"> should have a type attribute <script type="text/javascript">
setInterval("Count()",1000); works, but can also be rewritten as setInterval(Count,1000);
With these changes it is working.

Related

Forcing AngularJS to reload updated value on html end

I have a timer that I am writing as my first application in AngularJS. I have been trying to teach myself angular but I believe there may be a fundamental disconnect in how I have my model set up. Although I can see the updated values in the web console via my console.log print outs, the timer on the html side is not appearing to update.
var myApp = angular.module('countdownTimer', []);
myApp.service('timerService',['$http','$timeout', function($http, $timeout){
var time = 180;
var self = this;
this.getPrettyTime = function(){
var minutes = time/60;
var seconds = time - minutes * 60;
if (seconds < 10){
myDateObject.date = minutes + ":0" + seconds;
}
else{
myDateObject.date = minutes + ":" + seconds;
}
return myDateObject;
}
var myDateObject = {
date: null
}
var onTimeout = function() {
time = time - 1;
if (time > 0){
console.log(time);
mytimeout = $timeout(onTimeout, 1000);
}
else{
time = 180;
mytimeout = $timeout(onTimeout, 1000);
}
}
this.start = function() {
$timeout(onTimeout, 1000);
}
}]);
myApp.controller('CounterController', ['$timeout','$scope', 'timerService', function($timeout, $scope, timerService){
/**$scope.counter = 180;
**/
//var date = new Date(null);
//date.setSeconds(timerService.getTime());
$scope.myDateObject = timerService.getPrettyTime();
$scope.start = function(){
timerService.start();
}
$scope.stop = function(){
$timeout.cancel(mytimeout);
}
}]);
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Example </title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<script src="app2.js"></script>
</head>
<body data-ng-app="countdownTimer">
<div data-ng-controller="CounterController">
{{myDateObject.date}}
<button data-ng-click="stop()">Stop</button>
<button data-ng-click="start()">Start</button>
</div>
</body>
</html>
As you can see in the example above, the timer is not updating on the webpage. Is there a disconnect in my logic (I am new to angular so I would love to learn where I went wrong) or am I misinterpreting angular functionality altogether?
Thanks
First, in getPrettyTime you need to do :
var minutes = Math.floor(time/60);
Else you will get a float number.
After that you need to call your getPrettyTime function every time your time is updated, so you can do this in your onTimeout function like this :
var onTimeout = function() {
time = time - 1;
self.getPrettyTime();
...
Here is a working snippet :
var myApp = angular.module('countdownTimer', []);
myApp.service('timerService', ['$http', '$timeout', function($http, $timeout) {
var time = 180;
var self = this;
self.getPrettyTime = function() {
var minutes = Math.floor(time / 60);
var seconds = time - minutes * 60;
if (seconds < 10) {
myDateObject.date = minutes + ":0" + seconds;
} else {
myDateObject.date = minutes + ":" + seconds;
}
return myDateObject;
}
var myDateObject = {
date: null
}
var onTimeout = function() {
time = time - 1;
self.getPrettyTime();
if (time > 0) {
console.log(time);
mytimeout = $timeout(onTimeout, 1000);
} else {
time = 180;
mytimeout = $timeout(onTimeout, 1000);
}
}
this.start = function() {
$timeout(onTimeout, 1000);
}
}]);
myApp.controller('CounterController', ['$timeout', '$scope', 'timerService', function($timeout, $scope, timerService) {
/**$scope.counter = 180;
**/
//var date = new Date(null);
//date.setSeconds(timerService.getTime());
$scope.myDateObject = timerService.getPrettyTime();
$scope.start = function() {
timerService.start();
}
$scope.stop = function() {
$timeout.cancel(mytimeout);
}
}]);
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Example </title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<script src="app2.js"></script>
</head>
<body data-ng-app="countdownTimer">
<div data-ng-controller="CounterController">
{{myDateObject.date}}
<button data-ng-click="stop()">Stop</button>
<button data-ng-click="start()">Start</button>
</div>
</body>
</html>

storing user input as var

So this is a timer that computes orders per hour. when i hard code the orders everything works the way i want it. but i can't seem to figure how to get user input to set the amount of orders. this is what I've been trying and it is not working. any ideas??
<html>
<body>
<p><strong>Time Elapsed:</strong><span id="time-elapsed"</span></p>
<button onclick="openFunc()">Start Time</button>
<button onclick="myStopFunction()">Stop time</button><br><br>
<input type="text" id="orderAmount"><br>Enter Number of Orders</input><br><br>
<button onclick="calculate(timeElapsed, orders)">Calculate...</button>
<script>
var timeElapsed = 0;
var myVar = '';
var average = 0;
var orders = document.getElementById("orderAmount").innerHTML += orders;
function openFunc(){
start();
}
function calculate(time, _orders) {
var avg = _orders/(time/_orders);
if (avg<1){
avg = 1;
}
document.write(avg + " Bags per Hour");
}
function start() {
if ( myVar != "" ) {
console.log('timer is running');
return;
}
clearInterval(myVar);
myVar = setInterval(function(){
myTimer()
}, 1000);
}
function myTimer() {
timeElapsed += 1;
document.getElementById("time-elapsed").innerHTML = formatTime(timeElapsed);
}
function formatTime(time) {
var hours = formatNumber(Math.floor(time/3600))
var minutes = formatNumber(Math.floor(time/60));
var seconds = formatNumber(time%60);
//console.log('minutes: ', minutes);
//console.log('seconds: ', seconds);
return hours + ":" + minutes + ":" + seconds
}
function formatNumber(number) {
if ( number < 10 ) {
return 0 + '' + number
}
return number
}
function myStopFunction() {
clearInterval(myVar);
myVar = "";
}
</script>
</body>
</html>
This is how you get user input from text field with orderAmount id:
var orders = document.getElementById("orderAmount").value;

Can't get form to hide in JS

Having this problem with trying to get a form to hide in Javascript.
Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<title>Timer</title>
<link rel="stylesheet" href="style.css">
<script src="javascript.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Roboto:400,300' rel='stylesheet' type='text/css'>
</head>
<body>
<div id="wrapper">
<div id="time">00:00:00</div>
<form id="myform">
<input type="text" autocomplete="off" id="box" placeholder="00:00:00" onkeypress="checkBox(event)">
</form>
</div>
</body>
</html>
And here is my JS:
function timer(time) {
document.getElementById("myform").style.display = "none";
document.getElementById("time").style.display = "inline";
var interval = setInterval(function () {
if (time == 0) {
time = 299;
} else {
var newTime = timeFormat(time);
document.getElementById("time").innerHTML = newTime;
document.title = newTime;
time--;
}
}, 1000);
}
function checkBox(event) {
if (event.keyCode == 13) {
var string = document.getElementById("box").value;
var numTest = string;
if (string.length != 0) {
var numOfColons = string.split(":").length - 1;
var hr = 0;
var min = 0;
var sec = 0;
if (numOfColons == 2) {
numTest = numTest.replace(":", "");
numTest = numTest.replace(":", "");
hr = string.substring(0, string.indexOf(":"));
string = string.replace(string.substring(0, string.indexOf(":")+1), "");
min = string.substring(0, string.indexOf(":"));
string = string.replace(string.substring(0, string.indexOf(":")+1), "");
sec = string.substring(0, string.length);
} else if (numOfColons == 1) {
numTest = numTest.replace(":", "");
min = string.substring(0, string.indexOf(":"));
string = string.replace(string.substring(0, string.indexOf(":")+1), "");
sec = string.substring(0, string.length);
} else if (numOfColons == 0) {
sec = string;
}
hr = parseInt(hr);
min = parseInt(min);
sec = parseInt(sec);
if(/^\d+$/.test(numTest)) {
var totalSec = hr*3600 + min*60 + sec;
if (totalSec > 0) {
timer(totalSec);
}
}
}
}
}
function focus() {
document.getElementById("box").focus();
}
function timeFormat(time) {
var sec = time % 60;
var totalMin = time / 60;
var min = Math.floor(totalMin % 60);
var string = "";
if (min == 0 && sec < 10) {
string = "0:0" + sec;
} else if (min == 0) {
string = "0:" + sec;
} else if (sec < 10) {
string = min + ":0" + sec;
} else {
string = min + ":" + sec;
}
return string;
}
Note that I am not using a button to trigger the form submission, I am simply using a onkeypress event to detect if the user hit the enter button (I wanted a cleaner design). Whenever the timer function is called, the text box flickers like it turns off for a second, than it comes back on in an instant. I have no idea what the problem is. I also have gotten no errors in console.
Am not sure what you are trying to achieve but from looking at your code, Hitting enter results in the page being reloaded, so I can't get to see the result.
I would however suggest you use jQuery to hide show your results, since you are already calling the script
$('#myform').hide();
$('#time').show();
The problem is this line of code. It turns the form off for a split second, which causes the blinking effect to occur. Simply remove this or comment it out.
document.getElementById("myform").style.display = "none";
If you want to hide the form, use jQuery's $('#myForm').hide() function. It's similar to <form id="myform" style="display:none;">
You could also try this:
<input type="text" id="timeInputBox" autocomplete="off" id="box" placeholder="00:00:00" onkeypress="checkBox(event)">
With this:
document.getElementById('timeInputBox').style.display = "none"; // JS
Or use this:
$('#timeInputBox').hide(); // jQuery
You may also want to move the jQuery <script> tag up higher in your <head> block. It needs to go before your call to your external <script src="javascript.js"></script> tag. Then you can use the $ and all of these functions from api.jquery.com in your .js file.

JS function stopwatch application confuses the user

I wrote a javascript application but I end up with a total confusion. This js application needs to run in minutes, seconds, and hundredths of seconds. The part about this mess is when the stopwatch show, in this case 03:196:03. Here is my confusion. When the stopwatch shows 196, is it showing hundredth of seconds? Does anybody can check my function and tell me what part needs to be corrected in case that the function is wrong?
<html>
<head>
<title>my example</title>
<script type="text/javascript">
//Stopwatch
var time = 0;
var started;
var run = 0;
function startWatch() {
if (run == 0) {
run = 1;
timeIncrement();
document.getElementById("countDown").disabled = true;
document.getElementById("resetCountDown").disabled = true;
document.getElementById("start").innerHTML = "Stop";
} else {
run = 0;
document.getElementById("start").innerHTML = "Resume";
}
}//End function startWatch
function watchReset() {
run = 0;
time = 0;
document.getElementById("start").innerHTML = "Start";
document.getElementById("output").innerHTML = "00:00:00";
document.getElementById("countDown").disabled = false;
document.getElementById("resetCountDown").disabled = false;
}//End function watchReset
function timeIncrement() {
if (run == 1) {
setTimeout(function () {
time++;
var min = Math.floor(time/10/60);
var sec = Math.floor(time/10);
var tenth = time % 10;
if (min < 10) {
min = "0" + min;
}
if (sec <10) {
sec = "0" + sec;
} else if (sec>59) {
var sec;
}
document.getElementById("output").innerHTML = min + ":" + sec + ":0" + tenth;
timeIncrement();
},10);
}
} // end function timeIncrem
function formatNumber(n){
return n > 9 ? "" + n: "0" + n;
}
</script>
</head>
<body>
<h1>Stopwatch</h1>
<p id="output"></p>
<div id="controls">
<button type="button" id ="start" onclick="startWatch();">Start</button>
<button type="button" id ="reset" onclick="watchReset();">Reset</button>
</div>
</body>
</html>
Your code is totally weird!
First you're using document.getElementById() for non-existing elements: maybe they belong to your original code and your didn't posted it complete.
Then I don't understand your time-count method:
you make timeIncrement() to be launched every 10 ms: so time/10 gives you a number of milliseconds
but you compute min and sec as if it was a number of seconds!
From there, all is wrong...
Anyway IMO your could make all that simpler using the getMilliseconds() function of the Date object.
Try this:
document.getElementById("output").innerHTML = [
Math.floor(time/100/60 % 60),
Math.floor(time/100 % 60),
time % 100
].map(formatNumber).join(':')
var time = 0;
var started;
var run = 0;
function startWatch() {
if (run == 0) {
run = 1;
timeIncrement();
} else {
run = 0;
}
}
function watchReset() {
run = 0;
time = 0;
document.getElementById("output").innerHTML = "00:00:00";
}
function timeIncrement() {
if (run == 1) {
setTimeout(function () {
time++;
document.getElementById("output").innerHTML = [
Math.floor(time/100/60 % 60),
Math.floor(time/100 % 60),
time % 100
].map(formatNumber).join(':')
timeIncrement();
},10);
}
}
function formatNumber(n){
return (n < 10 ? "0" : "") + n;
}
startWatch()
<div id="output"></div>

setInterval doesn't work, what might be wrong?

i'm creating a count down time, and here is my piece of code, but it just doesn't work, what might i be doing wrong?
<div id="container">
<h1 id="time">0:00</h1>
</div>
<script type="text/javascript">
$(document).ready(function(){
var minutes = 1;
var secondsRemaining = minutes * 60;
intervalHandle = setInterval(tick,1000);
function tick(){
var timeDisplay = $('#time');
var min = Math.floor(secondsRemaining / 60);
var sec = secondsRemaining - (min * 60);
if(sec < 0){
sec = "0" + sec;
}
var message = min.toString() + ":" + sec;
timeDisplay.html(message);
if(secondsRemaining === 0){
alert('Done!');
clearInterval(intervalHandle);
resetPage();
}
}
});
</script>
`
You forgot to decrease the seconds each step :-) they are still equal to 60:
secondsRemaining--;
Here's fiddle;
http://jsfiddle.net/GhnMr/

Categories