I (a javascript newbie) want to have mutiple clocks with different time values in one page.
I managed to get the clock running, but if i add a second clock only one clock is getting displayed. In the console both ids with the correct (different) time are printed.
(function($, undefined) {
$.fn.clock = function(currentTime) {
return this.each(function() {
var localTime = +Date.now();
var timeDiff = currentTime - localTime;
updateClock = function (self, diff) {
var realtime = +Date.now() + diff;
var date = new Date(realtime);
var hours = date.getHours();
if(hours < 10) hours = "0"+hours;
var minutes = date.getMinutes();
if(minutes < 10) minutes = "0"+minutes;
var seconds = date.getSeconds();
if(seconds < 10) seconds = "0"+seconds;
var day = date.getDate();
var month = date.getMonth()+1;
var year = 1900 + date.getYear();
if(day < 10) day = "0"+day;
if(month < 10) month = "0"+month;
var formattedTime = day + '.' + month + '.' + year + ' ' + hours + ':' + minutes + ':' + seconds;
self.text(formattedTime);
console.log(self.attr("id")+":"+formattedTime);
setTimeout(function() {updateClock(self, diff)}, 1000);
};
updateClock($(this), timeDiff);
});
};
return this;
})(jQuery);
Call (takes time in ms as parameter):
<script type="text/javascript">
$(document).ready(function() {
$("#clock").clock(123456789);
$("#clock2").clock(1234567899);
});
</script>
clock and clock2 are empty divs.
Problem: Only clock2 (the last initialized clock) is displaying the time.
EDIT:
DIVs:
<div id="clock"/>
<div id="clock2"/>
EDIT2:
It's working now. The divs need an end-tag.
updateClock is a implicitly global variable. Add a var, or make it
function updateClock(self, diff) {
to scope the function correctly.
Div's must have end tag
Tag omission None, both the starting and ending tag are mandatory.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div
<div id="clock"></div>
<div id="clock2"></div>
Related
I am creating task again service and each service has number of hours
so when i log manually log time i want datetimepicker to only log reaming number of seconds
EX:
Step 1. service contain 2hr
Step 2. I logged 1hr
Step 3. Now I want to add validation that user should only add reaming time in datetimepicer(1hr)
Here is my code
<script type="text/javascript">
var timezone_offset_minutes = Intl.DateTimeFormat().resolvedOptions().timeZone;
$('#timezone').val(timezone_offset_minutes);
$('#startTime, #endTime').timepicker({
minuteStep: 1,
showSeconds: true,
secondStep: true,
}).on('hide.timepicker', function (e) {
calculateTime();
});
jQuery('#start_date, #end_date').datepicker({
autoclose: true,
todayHighlight: true,
}).on('hide', function (e) {
calculateTime();
});
calculateTime();
function calculateTime() {
var startDate = $('#start_date').val();
var endDate = $('#end_date').val();
var startTime = $("#startTime").val();
var endTime = $("#endTime").val();
var timeStart = new Date(startDate + " " + startTime);
var timeEnd = new Date(endDate + " " + endTime);
var diff = (timeEnd - timeStart) / 60000; //dividing by seconds and milliseconds
var minutes = diff % 60;
var hours = (diff - minutes) / 60;
var seconds = Math.floor(minutes * (60));
var calSeconds = seconds % 60;
if (hours < 0 || minutes < 0) {
var numberOfDaysToAdd = 1;
timeEnd.setDate(timeEnd.getDate() + numberOfDaysToAdd);
var dd = timeEnd.getDate();
if (dd < 10) {
dd = "0" + dd;
}
var mm = timeEnd.getMonth() + 1;
if (mm < 10) {
mm = "0" + mm;
}
var y = timeEnd.getFullYear();
$('#end_date').val(mm + '/' + dd + '/' + y);
calculateTime();
}
else {
$('#total_time').html(hours + " Hours " + Math.floor(minutes) + " Minutes " + calSeconds + " Seconds ");
}
}
</script>
and here is remaing number of seconds i am getting from controller
{{$subsSeconds}} //9 seconds
If I were you, I wouldn't validate these things in javascript, since this is executed on the user's computer, but in PHP on your server.
Since you're using PHP, you could use the PHP date() functions, or use an external library to calculate if the given date is past a certain point.
If you really want to do date calculations in javascript, Moment.js (https://momentjs.com/) is a pretty good javascript library for dealing with dates. Since plain old javascript isn't very good for dealing with dates (in my opinion).
I have the following piece of JavaScript which currently displays a digital clock on my webpage. I am creating a web based interactive story which is based on a day in the office. Everytime the user clicks a button to proceed onto the next part of the story I want to increment the clock by 30 minutes. Currently the clock is just showing real time. Ideally it would need to start at 9:00 am for the story then increment as the user goes through.
I have absolutely no idea how to do this and am fairly new to JavaScript, hopefully someone can help!
function displayTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var meridiem = "am"; // Default is AM
if (hours > 12) {
hours = hours - 12; // Convert to 12-hour format
meridiem = "PM"; // Keep track of the meridiem
}
if (hours === 0) {
hours = 12;
}
if(hours < 10) {
hours = "0" + hours;
}
if(minutes < 10) {
minutes = "0" + minutes;
}
if(seconds < 10) {
seconds = "0" + seconds;
}
var clockDiv = document.getElementById('clock');
clockDiv.innerText = hours + ":" + minutes + ":" + seconds + " " + meridiem;
}
displayTime();
setInterval(displayTime, 1000); });
To start at 09:00 o'clock, you could use
var d = new Date();
d.setHours(9);
d.setMinutes(0);
d.setSeconds(0);
Then, I would recommend using moment.js
function onClick() {
d = moment(d).add(30, "minutes").toDate();
var el = document.getElementById('clock');
el.innerHTML = moment(d).format("HH:mm:ss");
}
You can also do it without moment.js
function pad(t) {
return t < 10 ? "0" + t : t;
}
function onClick() {
d.setMinutes(d.getMinutes() + 30);
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var time = pad(h) + ":" + pad(m) + ":" + pad(s);
document.getElementById("clock").innerHTML = time;
}
JSFiddle Demo (moment.js)
JSFiddle Demo (vanilla)
Working code (jquery), but you need to modify it according to your needs,
function displayTime(currentTime, hours, minutes, seconds) {
var meridiem = "am"; // Default is AM
if (hours > 12) {
hours = hours - 12; // Convert to 12-hour format
meridiem = "PM"; // Keep track of the meridiem
}
if (hours === 0) {
hours = 12;
}
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
$('#clock').text(hours + ":" + minutes + ":" + seconds + " " + meridiem);
}
$(function() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
displayTime(currentTime, hours, minutes, seconds);
$('#increment30').on('click', function() {
currentTime.setMinutes(currentTime.getMinutes() + 30);
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
displayTime(currentTime, hours, minutes, seconds);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id='clock'>sss</div>
<button id='increment30'>INCREMENT 30</button>
Hi here is another one try here http://jsfiddle.net/Ltq9dhaw/ :
var time = new Date();
time.setHours(9);
time.setMinutes(0);
time.setSeconds(0);
function displayTime() {
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();
var meridiem = "am"; // Default is AM
if (hours > 12) {
hours = hours - 12; // Convert to 12-hour format
meridiem = "PM"; // Keep track of the meridiem
}
if (hours === 0) {
hours = 12;
}
if(hours < 10) {
hours = "0" + hours;
}
if(minutes < 10) {
minutes = "0" + minutes;
}
if(seconds < 10) {
seconds = "0" + seconds;
}
var clockDiv = document.getElementById('clock');
clockDiv.innerText = hours + ":" + minutes + ":" + seconds + " " + meridiem;
}
document.querySelector('#add').addEventListener('click',function(){
var minutes = 30;
time = new Date(time.getTime() + minutes*60000);
displayTime();
});
displayTime();
I'm gonna throw my hat in the ring here too.
var date = new Date(); // create a new Date object
date.setHours(9); // set it to 09:00:00
date.setMinutes(0);
date.setSeconds(0);
setInterval(function(){ // loop...
date.setSeconds(date.getSeconds()+1); // increment the seconds by 1
var str = ''; // build up a formatted string from the Date object
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
str += h.toString().length==1 ? '0' : ''; // if we have a single digit, prepend with a '0'
str += h;
str += ':'
str += m.toString().length==1 ? '0' : ''; // and again
str += m;
str += ':'
str += s.toString().length==1 ? '0' : ''; // and again
str += s;
$('#time').html(str); // set the element with ID 'time' to contain the string we just built
}, 1000); // ... every second
$('#increment').click(function(){ // when i click the element with id 'increment'
date.setMinutes(date.getMinutes()+30); // add 30 minutes to our Date object
});
Note that you will need to include jQuery on your page.
You can do that with the following snippet:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
Since you are using jQuery you can keep it simple:
function fmt2(v){return v<10?'0'+v:''+v;}
$(function(){
var t=new Date();t.setHours(9);t.setMinutes(0);t.setSeconds(0);
var offset=t.getTime() - new Date().getTime();
function displayTime(){
var currentTime= new Date((new Date()).getTime()+offset);
var hours = currentTime.getHours();
var meridiem=hours>=12?"PM":"AM";
hours=hours%12;
if (hours==0) hours=12;
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
$('#clock').text( fmt2(hours)+':'
+fmt2(minutes)+':'
+fmt2(seconds)+' '+meridiem);
}
$('#newtime').click(function(){offset+=60*30*1000;});
setInterval(displayTime,1000);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clock">09:00:00 AM</div>
<a id="newtime" href=#>add time</a>
I am working basically with the real time but there is an offset applied to it. The offset is calculated such, that the clock will always start at 9:00 AM.
So I made a little script for a clock, and used setInterval to make it live.
It works fine, but the problem is it freezes my browser after a minute or so. I'm a little stuck as I don't know how to solve this. Can someone help please?
Here is the code:
$(function liveClock(){
var dt = new Date();
var hh = dt.getHours();
var mm = dt.getMinutes();
var ss = dt.getSeconds();
var ampm = "";
if (ss <= 9){ ss = "0"+dt.getSeconds() }
if (mm <= 9){ mm = "0"+dt.getMinutes() }
if (hh > 12){
hh = hh - 12;
ampm = "pm";
}else{
ampm = "am";
}
$("p").html( hh + ":" + mm + ":" + ss + " " + ampm );
setInterval(function(){
liveClock();
}, 1000);
});
Thanks in advance
Every time liveClock runs, it starts an interval running.
You run it manually. You have an interval running that runs it every second.
After 1 second, it gets called again. You now have two intervals calling it every second.
After 2 seconds, it gets called again twice. You now have 4 intervals calling it every second.
3 seconds. 8 intervals.
4 seconds. 16 intervals.
etc.
Replace $() with setInterval
Remove setInterval from inside the function
I think it's because your setting setInterval every time the function is run, and so after a minute you have 60 timers going.
You can make it work correctly by only setting setInterval once like so:
function liveClock(){
var dt = new Date();
var hh = dt.getHours();
var mm = dt.getMinutes();
var ss = dt.getSeconds();
var ampm = "";
if (ss <= 9){ ss = "0"+dt.getSeconds() }
if (mm <= 9){ mm = "0"+dt.getMinutes() }
if (hh > 12){
hh = hh - 12;
ampm = "pm";
}else{
ampm = "am";
}
$("p").html( hh + ":" + mm + ":" + ss + " " + ampm );
}
$(function() {
setInterval(function(){
liveClock();
}, 1000);
});
JSFiddle here: http://jsfiddle.net/76328/
Or try exchanging it for setTimeout() instead which will only happen once.
Try this:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="Scripts/jquery-1.4.1.min.js"></script>
<script>
function liveClock() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
$("p").html(h + ":" + m + ":" + s);
var t = setTimeout(function () { liveClock() }, 500);
}
function checkTime(i) {
if (i < 10) { i = "0" + i }; // add zero in front of numbers < 10
return i;
}
</script>
</head>
<p></p>
Fiddle here
This code doesn't freezes browser and I've checked it and it works perfectly. Hope to get vote up for the code.
I am using following code to display date on my webpage. I need to update it every minute. How to do that?
var d=new Date();
var n=d.toString();
document.write(n);
Currently its static, means when the page load, datetime of that moment is displayed. I have to update time every minutes without refreshing the page.
Try with setInterval(): http://jsfiddle.net/4vQ8C/
var nIntervId; //<----make a global var in you want to stop the timer
//-----with clearInterval(nIntervId);
function updateTime() {
nIntervId = setInterval(flashTime, 1000*60); //<---prints the time
} //----after every minute
function flashTime() {
var now = new Date();
var h = now.getHours();
var m = now.getMinutes();
var s = now.getSeconds();
var time = h + ' : ' + m + ' : ' + s;
$('#my_box1').html(time); //<----updates the time in the $('#my_box1') [needs jQuery]
}
$(function() {
updateTime();
});
You can use document.getElementById("my_box1").innerHTML=time; instead of $('#my_box1')
from MDN:
About setInterval : --->Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
About setTimeout : ----> Calls a function or executes a code snippet after specified delay.
Here is how you can print date time every second
function displayDate()
{
var n=BuildDateString();
document.write(n);
window.setTimeout("displayDate();", 1000); // to print it every minute take 1000*60
}
function BuildDateString()
{
var today = new Date()
var year = today.getYear()
if (year < 2000)
year = "19" + year
var _day = today.getDate()
if (_day < 10)
_day = "0" + _day
var _month = today.getMonth() + 1
if (_month < 10)
_month = "0" + _month
var hours = today.getHours()
var minutes = today.getMinutes()
var seconds = today.getSeconds()
var dn = "AM"
if (hours > 12)
{
dn = "PM"
hours = hours - 12
}
if (hours == 0)
hours = 12
if (minutes < 10)
minutes = "0" + minutes
if (seconds < 10)
seconds = "0" + seconds
var DateString = _month+"/"+_day+"/"+year+" "+hours+":"+minutes+":"+seconds+" "+dn
return DateString;
}
I am using following approach:
var myVar=setInterval(function(){myDateTimer()},60000);
function makeArray()
{
for (i = 0; i<makeArray.arguments.length; i++)
this[i + 1] = makeArray.arguments[i];
}
function myDateTimer()
{
var months = new makeArray('January','February','March','April','May',
'June','July','August','September','October','November','December');
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;
var hours = date.getHours();
var minutes = date.getMinutes();
var finaldate = days[ date.getDay() ] + ", " + months[month] + " " + day + ", " + year + " " + hours +" : " + minutes;
document.getElementById("showDateTime").innerHTML=finaldate;
}
just do this
$(function(){
setInterval(function(){
var d=new Date();
var n=d.toString();
$('#test').html(n);
},1000);
});
demo http://runjs.cn/code/txlexzuc
Let me first say I do not have a deep understanding of javascript but I know how to work my way around enough to write small scripts for pages. A client of mine needs me to do the following for a website:
Find the user's local time on their computer.
Take that local time and subtract it from 6pm.
Display that time in a countdown or just a statement letting the user know how much time is left for same day shipping.
After 6pm the time resets or disappears until the next business day.
So far I've been able to create the logic for getting the time from the local computer. I thought I'd be able to use datejs but it does not calculate hours in a day.
Here is the current code I have:
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var suffix = "AM";
if (hours >= 12)
{
suffix = "PM";
hours = hours - 12;
}
var suffix = "AM";
if (hours >= 12)
{
suffix = "PM";
hours = hours - 12;
}
if (hours == 0)
{
hours = 12;
}
if (minutes < 10)
minutes = "0" + minutes;
document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>");
How about this:
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (minutes < 10)
minutes = "0" + minutes
if (suffix == "PM" && hours >= 6)
{
document.write("You're too late for next day shipping!");
}
else
{
var hoursLeft = 5 - hours;
var minsLeft = 60 - minutes;
document.write("<b> You've got " + hoursLeft + " hours and " + minsLeft + " minutes left to qualify for next day shipping! </b>")
}
if this site would let me comment on other people's answers I'd give the credit for this to Giovanni, but since I can't yet comment on other people's work, here's what needs to change.
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var suffix = "AM";
if (minutes < 10)
minutes = "0" + minutes
if (hours >= 18)
{
document.write("You're too late for next day shipping!");
}
else
{
var hoursLeft = 17 - hours;
var minsLeft = 60 - minutes;
if(minsLeft==60){
minsLeft=0;
hoursLeft++;
}
document.write("<b> You've got " + hoursLeft + " and " + minsLeft + " minutes left to qualify for next day shipping! </b>")
}
The reason for this is that people who are ordering at 5AM might see think that they have to submit within the next hour for their shipping to be next day when in fact they have the next 13 hours.
EDIT: saw your timezone concern and here is a post that might interest you.
EDIT 2: posted the wrong link. The correct one should be up now, though it might be a bit of a dated answer.
Something similar I solved also yesterday, so this is easy. Here is the javascript code:
function start_onload(last_hour){
var timeout_message = document.getElementById('timeout_message');
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var expire_time = 0; // in seconds
if (hours<last_hour) {
expire_time += (last_hour-hours-1)*3600;
expire_time += (59-minutes)*60;
expire_time += (59-seconds);
}
else {
timeout_message.innerHTML = 'It\'s after '+last_hour+' o\'clock!';
return;
}
var expire_time = currentTime.getTime() + 1000*expire_time;
//console.log(expire_time, hours, minutes, seconds, expire_time);
function countdown_session_timeout() {
var current_time = new Date().getTime();
var remaining = Math.floor((expire_time - current_time)/1000);
if (remaining>0) {
hours = Math.floor(remaining/3600);
minutes = Math.floor((remaining - hours*3600)/60);
seconds = remaining%60;
timeout_message.innerHTML = 'Countdown will stop in '+ hours + ' hours ' + minutes + ' min. ' + seconds + ' sec.';
setTimeout(countdown_session_timeout, 1000);
} else {
timeout_message.innerHTML = 'Time is up!';
}
}
countdown_session_timeout();
}
Full script # pastebin.com is here.
This is a simple countdown timer starting at 30 seconds from when the function is run and ending at 0. After reaching 0 it automatically reset the counter. It goes again to 30 second and this process is continued in a loop
window.onload = function() { startCountDown(30,
1000, myFunction); }
function startCountDown(i, p, f) { var pause = p; var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
//write out count
countDownObj.innerHTML = i;
if (i == 0) {
//execute function
//fn();
startCountDown(30, 1000, myFunction); //stop
return; } setTimeout(function() {
// repeat
countDownObj.count(i - 1);
},
pause
); } //set it going countDownObj.count(i); }
function myFunction(){};
</script>