a simple date in javascript - 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>

Related

YouTuve IFrame API trouble with playerVars

I want to start my video at certain times of the day. This is 'script.js':
var player;
function createPlayer() {
player=new YT.Player('main-block',{
height:'400',
width:'400',
playerVars:{
'rel':0,
'controls':0,
'showinfo':0,
'disablekb':1,
'modestbranding':1,
'enablejsapi':1
},
videoId:'tgbNymZ7vqY',
events:{
'onReady':onPlayerReady
}
});
}
function onPlayerReady(event) {
document.getElementById("timer").style.display='none';
event.target.playVideo();
}
function clockPlayer(){
var now = new Date();
if (now.getHours()==20 && now.getMinutes()==18){
createPlayer();
}else if(now.getHours()<20){
var time_hours = 19 - now.getHours();
var time_min = 59 - now.getMinutes();
var time_sec = 59 - now.getSeconds();
var hours=((time_hours<10) ? "0":"") + time_hours;
var min=((time_min<10)? "0":"") + time_min;
var sec=((time_sec<10)? "0":"") + time_sec
var time = hours + ':' + min + ':' + sec;
document.getElementById("timer").innerHTML=time;
}
}
setInterval(clockPlayer, 1000);
When I try to call this function my browser ignores 'playerVars', I can't understand why.
This is index.html:
<body>
<script language="javascript" src="https://www.youtube.com/iframe_api"></script>
<div id="timer"></div>
<div id="main-block"></div>
<script language="javascript" src="script.js"></script>
</body>
The clock function has random date now, I will change it later. When I try to use createPlayer() without clock function, I have the same result.
You have a typo in your code.
Change widht to width.
If the the problem is still present, please provide more info.
PS. Install a linter to avoid typos ;)
Maybe the problem is in the else if section in of your code.
I changed like this and it works as expected:
if (now.getHours() == 1 && now.getMinutes() == 12) {
createPlayer();
} else {
var time_hours = 19 - now.getHours();
var time_min = 59 - now.getMinutes();
var time_sec = 59 - now.getSeconds();
var hours = ((time_hours < 10) ? "0" : "") + time_hours;
var min = ((time_min < 10) ? "0" : "") + time_min;
var sec = ((time_sec < 10) ? "0" : "") + time_sec
var time = hours + ':' + min + ':' + sec;
document.getElementById("timer").innerHTML = time;
}
This is the working jsfiddle with the following modifications:
I changed the if condition for create the player once the time is 12:49 - for testing purposes.
Remove the else if and set the else only.

how to create click event to display set interval time

I have a Javascript setInterval function set up to display like a timer. I'd like to display the time that is on the timer when a "next" button is clicked so the user can see how long they've spent on a certain page. I'm unsure how to connect the setInterval with a click event. This is what I have, but it's not working.
let timerId = setInterval(function () {
document.getElementById("seconds").innerHTML = pad(++sec % 60);
document.getElementById("minutes").innerHTML = pad(parseInt(sec / 60, 10));
}, 1000);
function myFunction() {
alert document.getElementById("timerId").innerHTML = "Time passed: " + timerId);
}
This should solve your problem.
var initialTime = new Date().getTime();
var timeSpent='0:00';
var timeElement = document.getElementById("time");
timeElement.innerHTML = timeSpent;
let timerId = setInterval(function () {
var currentTime = new Date().getTime();
timeSpent = millisToMinutesAndSeconds(currentTime - initialTime)
timeElement.innerHTML = timeSpent;
}, 1000);
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}
function alertFn(){alert(timeSpent)}
document.getElementById("rightButton").addEventListener('click',alertFn);
document.getElementById("wrongButton").addEventListener('click',alertFn);
<h1 id="time"></h1>
<button id="rightButton">Right</button>
<button id="wrongButton">Wrong</button>
First of all, it would be better if you put setInterval method inside the function. After that you could give your function to an event listener as an argument.
Your code should look something like this
let timerId;
function displayTime() {
timerId = setInterval(() => {
// your code
}, 1000);
}
document.querySelector('button').addEventListener('click', displayTime)

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

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.

Javascript not displaying in browser

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 "/"

Categories

Resources