Javascript not displaying in browser - javascript

I'm following a tutorial about creating a timer in JavaScript but I can't get it to show up on my browser. I'm using Dreamweaver and it shows the timer just fine in a "live view" but in the browser window nothing is being displayed. What am I missing?
This is the main HTML page:
<html>
<head>
<script type="text/javascript" src="/Timer2.js" />
</head>
<body>
<div id='timer' />
<script type="text/javascript">
window.onload = CreateTimer("timer", 90);
</script>
</head>
</body>
</html>
This is the JavaScript timer function. timer2.js:
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time) {
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function Tick() {
if (TotalSeconds <= 0) {
alert("Time's up!")
return;
}
TotalSeconds -= 1;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function UpdateTimer() {
Timer.innerHTML = TotalSeconds;
}
function UpdateTimer() {
var Seconds = TotalSeconds;
var Days = Math.floor(Seconds / 86400);
Seconds -= Days * 86400;
var Hours = Math.floor(Seconds / 3600);
Seconds -= Hours * (3600);
var Minutes = Math.floor(Seconds / 60);
Seconds -= Minutes * (60);
var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)
Timer.innerHTML = TimeStr ;
}
function LeadingZero(Time) {
return (Time < 10) ? "0" + Time : + Time;
}

You can't self-close a script tag. You MUST write <script ....></script>

Write <div id="timer"></div> and no <div id='timer' />
Delete your </head> at the bottom of the code, and if your script doesn't work again, try src="Timer2.js" without the "/"

Related

javascript function is not working on button click. But working without button click

In this function, I have implemented a timer which is working fine in the given html input box without onclick function 'start_test'. but i want to start this inner function on button click which is not working. PLease help me to find the mistake.
function start_test() {
var hms = "01:30:00";
var a = hms.split(':'); // split it at the colons
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
if( seconds > 0 ){
function secondPassed() {
var minutes = Math.round((seconds - 30)/60),
remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = " " +minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
//form1 is your form name
document.form_quiz.submit();
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
}
}
<div class="col-md-4" style="text-align: right;">
<button class="btn btn-primary" id="start_test" onclick="start_test();" >Start Test</button>
<input type="hidden" value="<?php echo date('M d Y');?>" id="c_month">
<h2><time id="countdown">01:30:00</time> </h2>
</div>
in setInterval(timePassed, 1000) this is 1s or MORE
=> 1000mms is just an indication, the time elapsed depend of the proccessor usage
PROOF:
const one_Sec = 1000
, one_Min = one_Sec * 60
, one_Hour = one_Min * 60
, biDigits = t => t>9?t:`0${t}`
, c_pseudo = document.getElementById('countdownP')
, c_real = document.getElementById('countdownR')
, btTest = document.getElementById('bt-test')
;
btTest.onclick=()=>
{
btTest.disabled = true
let [t_h,t_m,t_s] = '01:30:00'.split(':').map(v=>+v)
, timeEnd = new Date().getTime() + (t_h * one_Hour) + (t_m * one_Min) + (t_s * one_Sec)
, timerRef = setInterval(timePassed, 1000) // 1s or MORE !
;
function timePassed()
{
if (--t_s <0) { t_s = 59; --t_m}
if (t_m <0) { t_m = 59; --t_h }
c_pseudo.textContent = `${biDigits(t_h)}:${biDigits(t_m)}:${biDigits(t_s)}`
let tim = timeEnd - (new Date().getTime())
let tr_h = Math.floor(tim / one_Hour)
let tr_m = Math.floor((tim % one_Hour) / one_Min )
let tr_s = Math.floor((tim % one_Min ) / one_Sec )
c_real.textContent = `${biDigits(tr_h)}:${biDigits(tr_m)}:${biDigits(tr_s)}`
if ( !t_h && !t_m && !t_s)
{
btTest.disabled = false
clearInterval(timerRef)
}
}
}
<button id="bt-test" >Start Test</button>
<h2> pseudo count down <span id="countdownP">01:30:00</span> </h2>
<h2> real count down <span id="countdownR">01:30:00</span> </h2>
This statement is declaring a function countdownTimer, not executing it.
var countdownTimer = setInterval('secondPassed()', 1000);
Try replacing with:
setInterval(() => secondPassed(), 1000);
This should actually execute setInterval

How can I modify my function to be able to cancel the interval from anywhere in the controller

I am trying to create a countdown and I want to be able to cancel the interval not only when reach 0 but with clicking of a button as well.How can I modify my function to be able to cancel the interval from anywhere in the controller.
function countDown(total) {
total = total * 60;
var interval = $interval(function () {
var minutes = Math.floor(total / 60);
var seconds = total - minutes * 60;
if (minutes < 1)
{
minutes = '0:';
}
else
{
minutes = minutes + ':';
}
if (seconds < 10)
{
seconds = '0' + seconds;
}
self.remainingTime = "Remaining time: " + minutes + seconds;
total--;
if(minutes === '0:' && seconds === '00')
{
$interval.cancel(interval);
}
}, 1000);
}
As suggested by other users, you should make interval global in the controller. Then on the other functions you want to cancel the interval you can call it safely.
Take a look at the below sample:
angular.module('app', [])
.controller('ctrl', function($interval) {
var self = this;
var interval;
self.wizard = {
startInterval: startInterval,
cancelInterval: cancelInterval
};
startInterval();
return self.wizard;
function startInterval() {
countDown(24);
}
function cancelInterval() {
$interval.cancel(interval);
}
function countDown(total) {
cancelInterval();
total = total * 60;
interval = $interval(function() {
var minutes = Math.floor(total / 60);
var seconds = total - minutes * 60;
if (minutes < 1) {
minutes = '0:';
} else {
minutes = minutes + ':';
}
if (seconds < 10) {
seconds = '0' + seconds;
}
self.wizard.remainingTime = "Remaining time: " + minutes + seconds;
total--;
if (minutes === '0:' && seconds === '00') {
$interval.cancel(interval);
}
}, 1000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<span ng-app="app" ng-controller="ctrl as ctrl">
<span ng-bind="ctrl.remainingTime"> </span>
<br/>
Cancel Interval
<br/>
Start Interval
</span>
I created an example using self instead of $scope like you are in your snippet above. As others mentioned moving the interval var to the global scope fixes this. I also added a stop and start function to test the issue you mentioned in the example above.
UPDATED - I added some code to the stop interval to reset the interval to undefined. I found an example of this usage on Angular's site so it might be worth a try to see if it fixes your other issue.
var app = angular.module('app', []);
app.controller('BaseController', function($interval) {
var self = this;
var interval;
function countDown(total) {
total = total * 60;
interval = $interval(function() {
var minutes = Math.floor(total / 60);
var seconds = total - minutes * 60;
if (minutes < 1) {
minutes = '0:';
} else {
minutes = minutes + ':';
}
if (seconds < 10) {
seconds = '0' + seconds;
}
self.remainingTime = "Remaining time: " + minutes + seconds;
total--;
if (minutes === '0:' && seconds === '00') {
$interval.cancel(interval);
}
}, 1000);
}
self.stopInterval = function(){
if (angular.isDefined(interval)) {
$interval.cancel(interval);
interval = undefined;
}
}
self.startInterval = function(){
countDown(10);
}
});
Then in the html I added a button to start and stop the interval like so:
<body ng-app="app">
<div ng-controller="BaseController as baseCtrl">
{{ baseCtrl.remainingTime }}
<div>
<button ng-click="baseCtrl.startInterval()">Start Countdown</button>
<button ng-click="baseCtrl.stopInterval()">Stop Countdown</button>
</div>
</div>
</body>
You can view the codepen example here

a simple date in javascript

please check my code, I've created a simple date in JS but it's not working, I'm following a tutorial and I have the exact code.
<html>
<head>
<title>Clock</title>
<script>
function time() {
var time = new Date();
var hours = time.getHours();
var mins = time.getMinutes();
var secs = time.getSeconds();
if (secs<10) {
secs = "0" + secs;
}
if (mins<10) {
secs = "0" + mins;
}
document.getElementById("thetime").innerHTML=hours+":"+mins+":"+secs;
var timer = setTimeout(function(){time()},500);
}
</script>
</head>
<body onload="time()">
<div id="thetime"></div>
</body>
</html>
You have function time() {...} and var time = new Date();. The local variable shadows the function, meaning that inside setTimeout(function(){time()},500);, time refers to the Date object, not the function.
Solution: Rename either of them.
Also,
replace this part of the code:
if (mins<10) {
secs = "0" + mins;
}
with this:
if (mins<10) {
mins= "0" + mins;
}
Try using setInterval() instead of timeout
function time() {
//Your stuff here...
}
var timer = setInterval(function(){time()},500);
Fiddle
Avoid using the same variable name as function name. It tried to call the variable as a function. Naming it currentTime makes it work.
function time() {
var currentTime = new Date();
var hours = currentTime.getHours();
var mins = currentTime.getMinutes();
var secs = currentTime.getSeconds();
if (secs<10) {
secs = "0" + secs;
}
if (mins<10) {
secs = "0" + mins;
}
document.getElementById("thetime").innerHTML=hours+":"+mins+":"+secs;
var timer = setTimeout(function(){time()},500);
}
You are naming a var var time the same your function time(). You should rename one of them.
For example name your function customTimer. You call this function from the setTimeout and from your onload in the html
<html>
<head>
<title>Clock</title>
<script>
function customTimer() {
var time = new Date();
var hours = time.getHours();
var mins = time.getMinutes();
var secs = time.getSeconds();
if (secs < 10) {
secs = "0" + secs;
}
if (mins < 10) {
mins = "0" + mins;
}
document.getElementById("thetime").innerHTML = hours + ":" + mins + ":" + secs;
var timer = setTimeout(function () { customTimer() }, 500);
}
</script>
</head>
<body onload="customTimer()">
<div id="thetime"></div>
</body>
</html>

Timer to be displayed on a webpage

I want to add a count up timer to my webpage, as in, a label that contains 0:00:00 should start displaying 0:00:01 and so on until the stop button is clicked.
Is there a simple javascript/jquery solution to this?
<html>
<head>
<title>Home</title>
<script src="jquery-1.11.1.js">
</script>
<script>
$(document).ready(function(){
$("p").click(function(){
//psst. psst.
});
});
</script>
</head>
<body>
<form>
<table>
<tr>
<td><input type="text" id="project" placeholder="project"></td>
<td><p id="timer">0:00:00<p></td>
</tr>
</table>
</form>
</body>
</html>
I tried something in Vanilla JS HERE
var seconds=0, minutes=0, hours=0;
var counter;
var stop,start;
var counting = false;
window.onload = function () {
counter = document.getElementById('counter');
stop = document.getElementById('stop');
stop.onclick = function () {
counting = false;
}
start = document.getElementById('start');
start.onclick = function() {
counting = true;
timer();
}
counting = true;
timer();
}
function timer() {
if (seconds >= 60) {
minutes++;
seconds = 0;
}
if (minutes >= 60) {
hours++;
minutes = 0;
}
counter.innerHTML = hours + ":" + minutes + ":" + seconds;
if (counting) {
seconds++;
setTimeout(timer, 1000);
}
}
If you need more info leave a comment..
time.js
function time(id)
{
date = new Date;
h = date.getHours();
if(h<10)
{
h = "0"+h;
}
m = date.getMinutes();
if(m<10)
{
m = "0"+m;
}
s = date.getSeconds();
if(s<10)
{
s = "0"+s;
}
result = h+':'+m+':'+s;
document.getElementById(id).innerHTML = result;
// "setTimeout" call function "time" every 1 second (1000 milliseconds)
setTimeout('time("'+id+'");','1000');
return true;
}
HTML
<html>
<head>
<title>Time in Javascript</title>
<script type="text/javascript" src="time.js"></script>
</head>
<body>
<span id="time"></span>
<script type="text/javascript">window.onload = time('time');</script>
</body>
</html>
Try this way
Use https://github.com/jchavannes/jquery-timer
Include this files in head
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript">
<script src="http://jchavannes.com/include/scripts/3p/jquery.timer.js" type="text/javascript">
Script
var Example1 = new (function() {
var $stopwatch, // Stopwatch element on the page
incrementTime = 70, // Timer speed in milliseconds
currentTime = 0, // Current time in hundredths of a second
updateTimer = function() {
$stopwatch.html(formatTime(currentTime));
currentTime += incrementTime / 10;
},
init = function() {
$stopwatch = $('#stopwatch');
Example1.Timer = $.timer(updateTimer, incrementTime, true);
};
this.resetStopwatch = function() {
currentTime = 0;
this.Timer.stop().once();
};
$(init);
});
function formatTime(time) {
var min = parseInt(time / 6000),
sec = parseInt(time / 100) - (min * 60),
hundredths = pad(time - (sec * 100) - (min * 6000), 2);
return (min > 0 ? pad(min, 2) : "00") + ":" + pad(sec, 2) + ":" + hundredths;
}
function pad(number, length) {
var str = '' + number;
while (str.length < length) {str = '0' + str;}
return str;
}
Example1();
DEMO
By using setInterval and Date
You can use button to stop and start timer.
var d = new Date();
d.setHours(0,0,0,0);
setInterval((function(){
return function(){
d.setSeconds(d.getSeconds()+1);
var t = d.toLocaleTimeString("en-US", {hour12: false});
document.getElementById("demo").innerHTML = t;
}
})(), 1000);
Fiddle Demo
Please try this fiddle for your solution.
JS.
var hour = 0;
var min = 0;
var second = 0;
var i=setInterval(function(){
second++;
if(second > 59){
second = 0;
min++;
if(min>59){
hour++;
min = 0;
}
}
var timer_time = (hour > 9 ? hour : '0'+hour)+':'+(min > 9 ? min : '0'+min)+':'+(second > 9 ? second : '0'+second);
$('#timer').html(timer_time);
}, 1000);
$('#stop_timer').click(function(){
clearInterval(i);
});
HTML
<p id='timer'>00:00:00</p>
<button id='stop_timer'>Stop Timer</button>
Thanks
Use timing events like documented at http://www.w3schools.com/js/js_timing.asp.

Trying to code improvement for JS countdown with localStorage

I'm not enough skilled in js and jq, and think this code looks really bad:
var updateTimerApple = function() {
var timerApple = localStorage.getItem('timerApple');
if ( timerApple < 0 ) {
$(".apple").css("display", "none");
}
else if (timerApple == 0) {
$(".apple").html("Apple ok").css("display", "block");
}
else {
timerApple--;
localStorage.setItem('timerApple', timerApple);
var hours = Math.floor(timerApple / 3600);
var minute = Math.floor((timerApple - (hours * 3600)) / 60);
var second = timerApple - (hours * 3600) - (minute * 60);
if (hours < 1) hours = "0" + hours;
if (minute < 10) minute = "0" + minute;
if (second < 10) second = "0" + second;
$(".apple").html("Apple tree:"+" "+hours+"ч"+" "+minute+"м"+" "+second+"с"+" ");
$(".apple").css("display", "block");
}
};
var updateTimeroak = function() {
var timeroak = localStorage.getItem('timeroak');
if ( timeroak < 0 ) {
$(".oak").css("display", "none");
}
else if (timeroak == 0) {
$(".oak").html("Oak ok").css("display", "block");;
}
else {
timeroak--;
localStorage.setItem('timeroak', timeroak);
var hours = Math.floor(timeroak / 3600);
var minute = Math.floor((timeroak - (hours * 3600)) / 60);
var second = timeroak - (hours * 3600) - (minute * 60);
if (hours < 1) hours = "0" + hours;
if (minute < 10) minute = "0" + minute;
if (second < 10) second = "0" + second;
$(".oak").html("Oak:"+" "+hours+"ч"+" "+minute+"м"+" "+second+"с"+" ");
$(".oak").css("display", "block");
}
};
$(function() {
setInterval(updateTimerApple, 1000);
$(".startApple").click( function() {
localStorage.setItem('timerApple', 51480);
$(".apple").removeAttr('style');
});
$(".apple").click( function() {
localStorage.removeItem('timerApple');
$(".apple").css({"display": "none", "visibility": "hidden","width":"0","height":"0", "padding":"0", "margin":"0"});
});
});
$(function() {
setInterval(updateTimeroak, 1000);
$(".startoak").click( function() {
localStorage.setItem('timeroak', 176400);
$(".oak").removeAttr('style');
});
$(".oak").click( function() {
localStorage.removeItem('timeroak');
$(".oak").css({"display": "none", "visibility": "hidden","width":"0","height":"0", "padding":"0", "margin":"0"});
});
});
<body>
<div class="content">
<div class="menu">
<button class="startApple">Apple</button>
<button class="startoak">Oak</button>
</div>
<div class="item apple"></div>
<div class="item oak"></div>
</div>
</body>
Or http://jsfiddle.net/38N6x/1/
It works fine, but I am trying to improve it, making it more generic.
Looking for something like this:
function updateTimer(n,t) {
this.n=n;
this.t=localStorage.getItem('n');
if ( t < 0 ) {
$(".apple").css("display", "none");
}
else if (t == 0) {
$(".apple").html("Apple ok").css("display", "block");
}
else {
this.t--;
localStorage.setItem('n', this.t);
var hours = Math.floor(t / 3600);
var minute = Math.floor((t - (hours * 3600)) / 60);
var second = t - (hours * 3600) - (minute * 60);
if (hours < 1) hours = "0" + hours;
if (minute < 10) minute = "0" + minute;
if (second < 10) second = "0" + second;
$(".apple").html("Apple tree:"+" "+hours+"ч"+" "+minute+"м"+" "+second+"с"+" ");
$(".apple").css("display", "block");
}
};
$(function() {
setInterval(updateTimer, 1000);
$(".startApple").click( function() {
var apple = new updateTimer ("apple", 23)
$(".apple").removeAttr('style');
});
$(".apple").click( function() {
localStorage.removeItem('apple');
$(".apple").css({"display": "none", "visibility": "hidden","width":"0","height":"0", "padding":"0", "margin":"0"});
});
});
But this code not works. Browser always returns NaN for $(".apple").html("Apple tree:"+" "+hours+"ч"+" "+minute+"м"+" "+second+"с"+" ");
Thx for any help.
After spending some time, i'm found the way for code optimisation.
JS
function catDate(catID, catTime) {
var s = new Date();
s.setSeconds(s.getSeconds() + catTime);
localStorage.setItem(catID, s);
}
function CountDownTimer(dt, id) {
var end = new Date(dt);
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
if (dt == 0) {
document.getElementById(id).style.display='none';
return;
}
else if(distance < 0) {
document.getElementById(id).innerHTML = 'Сan collect';
document.getElementById(id).style.display='block';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
document.getElementById(id).innerHTML = days + 'd ';
document.getElementById(id).innerHTML += hours + 'h ';
document.getElementById(id).innerHTML += minutes + 'm ';
document.getElementById(id).innerHTML += seconds + 's ';
document.getElementById(id).style.display='block';
}
timer = setInterval(showRemaining, 1000);
}
CountDownTimer(localStorage.getItem('apple'), 'apple');
CountDownTimer(localStorage.getItem('oak'), 'oak');
$(function() {
$(".startapple").click( function() {
catDate("apple", 5);
});
$("#apple").click( function() {
localStorage.setItem('apple', 0);
});
});
$(function() {
$(".startoak").click( function() {
catDate("oak", 2000);
});
$("#oak").click( function() {
localStorage.removeItem('oak');
});
});
$(function() {
$('div').click( function() {
location.reload();
});
});
HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Farm Frenzy</title>
<link rel="stylesheet" media="screen" href="css/style.css"/>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script type='text/javascript' src='js/items.js'></script>
<script type='text/javascript' src='js/itemscall.js'></script>
</head>
<body>
<div class="content">
<div class="menu">
<button class="startapple">Apple</button>
<button class="startoak">Oak</button>
</div>
<div id="apple" class="item"></div>
<div id="oak" class="item"></div>
</body>
</html>
But still have one problem: if user adding new timer (or setting localStorage.setItem('item', 0), for timer hiding), timer shows (or hiding) only after page refresh. Fixed this with
$(function() {
$('div').click( function() {
location.reload();
});
});
But i'm looking for better way.

Categories

Resources