Timed animated gif display - javascript

Noob Alert.....
I have searched previous questions and can not find this specific request.
For my Art project I have created an animated gif and want it to display/run my animated gif for just one hour per day on the website I have created for my other projects.
I have this script which is very similar but I need to automate the display (for one hour each day) and not on click or stepped. I can get rid of these stages but not sure on what to replace them with.
JavaScript Animation
<script type="text/javascript">
<!--
var imgObj = null;
var animate ;
function init(){
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
}
function moveRight(){
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
animate = setTimeout(moveRight,20); // call moveRight in 20msec
}
function stop(){
clearTimeout(animate);
imgObj.style.left = '0px';
}
window.onload =init;
//-->
</script>
Thank you in advance.....

Ok, first thing to notice is that you'll have to check the current time every now and then, to check if we're at that certain hour you want to show the animation.
Let's take as example: between 13h and 14h (1pm and 2pm)- from now on I'll use the 24h notation.
We can use an interval to check if it's past 13h already. We choose the precision ourselves. For the sake of the example, let's say that we check every 5 minutes:
//Note: we could say "300000" immediately instead, but with the calculation, we can easily change it when we want to.
var gifInterval = setInterval(function() {canWeAnimateYet ();}, 5 * 60 * 1000);
So, we got an interval that will check every 5 minutes. Now we need a flag (or bool) to see if the animation should run or not...
var animateThatGif = false;
And now.. We need the function to check the time:
var canWeAnimateYet = function() {
//Checks here.
}
On that function, we need to check the currenttime. If it's past 13 but before 14h, we need to put our flag to true, otherwise it stays false.
var canWeAnimateYet = function() {
//Get current time
//Note: "new Date()" will always return current time and date.
var time = new Date();
//Note: getHours() returns the hour of the day (between 0 and 23 included). Always in 24h-notation.
if (time.getHours() >= 13 && time.getHours < 14)
animateThatGif = true;
else
animateThatGif = false;
}

Related

Video loops and pauses

I'm making a web app for a gym, I need on a specific page to show a video of an exercise and repeat it for the number of repetitions, example 10 times, then I need to have a pause according to the set recovery time, example 60 seconds, and then I need to repeat this cycle for the set series, example 3.
This is the code that doesn't work for me:
$(document).ready(function() {
function sleep(milliseconds) {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
}
var player_video=document.getElementById("player");
var rep_video=parseInt(<?php echo($rep_video)?>);
var ser_video=parseInt(<?php echo($ser_video)?>);
var rec_video=parseInt(<?php echo($rec_video)?>);
rec_video = rec_video * 1000;
var count_rep=0;
var count_ser=0;
player_video.onended = function() {
if(count_ser<ser_video){
while(count_rep < rep_video){
player_video.src ="video/<?php echo($src_video)?>";
player_video.load();
player_video.play();
count_rep++;
}
count_ser++;
count_rep=0;
sleep(rec_video);
}
};
});
Might I suggest 1 video for your reps that you loop through, and a second video that shows the recovery countdown? That way - if they want to skip ahead, they can do so pretty easily.

Make a date/time value called from an API tick very second. (JavaScript)

I'm calling a date and time through an API, which looks like this:
<?php $xml = simplexml_load_file("https://api.eveonline.com/server/ServerStatus.xml.aspx/"); ?>
<div class="server-time">
<?php echo $xml->currentTime; ?>
</div>
This will show a date and time like this on the page:
2013-10-16 08:15:36
Now I want this clock to tick every second and the time and even date (in case it's just seconds before midnight when the user visits the site) values to change accordingly, just like you would expect a digital clock to work.
I know this is possible with JavaScript but since I am a total rookie at it I don't know how to do this - at all.
Help would be highly appriciated!
There are many javascript clocks out there, you don't even have to use an API to get the time and date!
function clock(id) {
//Create a new Date object.
oDate = new Date();
//Get year (4 digits)
var year = oDate.getFullYear();
//Get month (0 - 11) - NOTE this is using indexes, so 0 = January.
var month = oDate.getMonth();
//Get day (1 - 31) - not using indexes.
var day = oDate.getDate();
//Get hours
var hours = oDate.getHours();
//Get minutes
var minutes = oDate.getMinutes();
//Get seconds
var seconds = oDate.getSeconds();
//Maybe create a function that adds leading zero's here
var dateStr = '';
dateStr += year+' - '+month+' - '+day+' '+hours+':'+minutes+':'+seconds;
//Append dateStr to some element.
document.getElementById(id).innerHTML = dateStr;
//Repeat the function every 1000 miliseconds aka 1 second
setTimeout(function() {
clock(id);
}, 1000);
}
The usage would be
<div id="yourID">clock input will go here</div>
clock('yourID');
NOTE
This function has to be called after the DOM is loaded, otherwise this would result in error.
This can be achieved by placing the script tag with your JS at the bottom of the page (not using jQuery that is).
Otherwise if using jQuery, call the $(function() {}) (equivelant to $(document).ready(function() {});
The function is quite self-explanatory, but maybe you would want to read up on the functions to see exactly what they do.
a quick google search should do the trick.
Anyways hope this helps, good luck :)
I'm not sure if you want it to fetch the time from the api every second or, if you want it to just increase every second, starting from the given api time. In the latter case, you should use setInterval:
function updateTime() {
// assuming you are using jquery for DOM manipulation:
var timestamp = $('.server-time').text();
var date = new Date(timestamp);
date.setSeconds(date.getSeconds() + 1);
$('.server-time').text(date.toString());
}
setInterval(updateTime, 1000);
If you are not using jquery, just use document.getElementById or something like that:
change your element to:
<div id="server-time">
and use the following snippet:
function updateTime() {
// assuming you are using jquery for DOM manipulation:
var timestamp = document.getElementById('server-time').innerHTML;
var date = new Date(timestamp);
date.setSeconds(date.getSeconds() + 1);
document.getElementById('server-time').innerHTML = date.toString();
}

Performing an operation days or months in the future

I'm trying to figure out the best way to perform a task, e.g. send an email to a user, in the future.
My idea is to store (in a database along with users data) when the email needs to be sent, and on a daily basis check what users need emails sent, and use Meteor's Timer functions.
// 7 hours in millisec.
Meteor.setTimeout( function() {
Meteor.call( "sendReminderEmail", ... );
}, 2.52e+7 );
The problem that I see is having too many timers set up, and hindering performance. What is a good solution?
Edit: Basically my use case includes the user creating an event, which they set as a long term event or short term(based on days, weeks, or months), and they receive a follow-up on that event depending on the duration.
I guess I could check every hour, but that seems like a problem with equal cost. Is there a Meteor specific way to do this? Or just a better concept?
Edit2: Ok, I've realized that accurracy isn't that important for my problem, so I'm thinking of setting one timer per timezone, which would send bulk emails. If the user has a long term event and their reminder is this week, than send it now. Basically it depends on duration of event and timezone of user.
So my updated question is, how do I run something on a daily basis, with my problem in mind?
Let's say you want to execute a code at 9am today and now is 8am, you could create a timeout to match the minutes in the targeted time and then create a interval of 1 hour and at each execution check if the time is 9am, if it's, execute.
in this small scale example, I'm executing executeMe() when the clock shows 9 seconds:
Live Test: http://jsbin.com/ikulok/4/edit
<body>
Last run: <span id="time"></span><br>
Next execution: <span id="target"></span>
<script type="text/javascript">
function executeMe(){
alert("9 seconds!");
}
var timeout = null;
var interval = null;
function timer(){
var now = new Date();
document.getElementById('time').innerHTML = now;
document.getElementById('target').innerHTML = new Date(now.getTime()+ 1000);
//console.log("timer()", now);
if(now.getSeconds() == 9)
setTimeout("executeMe();",1); // async
if(interval == null)
interval = setInterval("timer()",1000);
}
var now = new Date();
var target = new Date(now.getFullYear(),now.getMonth(),now.getDate(),now.getHours(),now.getMinutes(),now.getSeconds()+1,0);
//console.log("now", now);
//console.log("target", target);
//console.log("diff", target.getTime() - now.getTime());
document.getElementById('target').innerHTML = target;
timeout = setTimeout("timer()", target.getTime() - now.getTime() );
</script>
If you want to run the timer() every hour instead of every second, just adjust the target and the setInterval() and of course your conditions
Live Test: http://jsbin.com/ikulok/3/edit
<body>
Last run: <span id="time"></span><br>
Next execution: <span id="target"></span>
<script type="text/javascript">
function executeMe(){
alert("1:20am!");
}
var timeout = null;
var interval = null;
function timer(){
var now = new Date();
document.getElementById('time').innerHTML = now;
document.getElementById('target').innerHTML = new Date(now.getTime()+ 1*60*60*1000);
//console.log("timer()", now);
if(now.getHour() == 1)
setTimeout("executeMe();", 20*60*1000); // !!!! this will execute at 1:20am
if(interval == null)
interval = setInterval("timer()",1*60*60*1000); // !!!! repeat every hour
}
var now = new Date();
// !!!! targeting next exact hour
var target = new Date(now.getFullYear(),now.getMonth(),now.getDate(),now.getHours(),now.getMinutes()+1,0,0);
//console.log("now", now);
//console.log("target", target);
//console.log("diff", target.getTime() - now.getTime());
document.getElementById('target').innerHTML = target;
timeout = setTimeout("timer()", target.getTime() - now.getTime() );
</script>
</body>

Change an image every minute using the computer's clock to time the changes

I want to change an image every minute. When the computer's clock moves from 8:50 to 8:51 then to 8:52 all the way back to 8:49 I want my picture to change from 0001.jpg to 0002.jpg to 0003.jpg all the way to 1440.jpg.
Since I am going to be using the computer's clock, I am interested in using JavaScript. I am also just starting out, so full code (which would be awesome!) is probably not what I need. Instead, I am looking for a place to start and maybe a direction to go. Any resources online that you know of would also be helpful
compute how many seconds until the next minute starts, then using setTimeout begin rotating the pictures. Use setInterval to do so every 60000 milliseconds.
var seconds = 60 - new Date().getSeconds();
setTimeout(function(){
console.log('start');
setInterval(function(){
console.log ('iterate over pictures here');
}, 1000 * 60);
}, seconds * 1000);
You can read more about both functions here
You'll want to study up on setInterval().
The code would look something like this:
var counter = 1,
lastUpdate = (new Date()).getTime(),
img = document.getElementById('image'); // Assuming your HTML has an img tag
// with an id of "image"
// This function just pads your number with 0s
function pad(num) {
var padding = '',
i = 4 - num.toString().length;
while (i > 0) {
padding += '0';
i -= 1;
}
return padding + num;
}
// This function is what actually does the updating
function update() {
var now = (new Date()).getTime();
if (lastUpdate + 1000 <= now) {
lastUpdate = now;
img.src = pad(counter) + '.jpg'; // change the image
counter += 1; // increment the counter
if (counter > 1440) { // reset to 1 if we get to our last image
counter = 1;
}
}
}
// Run update every 10th of a second
setInterval(update, 100);
The Mozilla Developer Center site has lots of great JavaScript and DOM references. I would also suggest learning to use JSLint, it will help a lot in avoiding stupid syntax errors that will cause headaches. I would suggest reading Douglas Crockford's book JavaSript: The Good Parts and Stoyan Stefanov's Object-Oriented JavaScript they are both excellent books to learn JavaScript from.
Place the code below in the BODY of a page:
<img />
<script>
var start = new Date().getTime(),
i = 0,
//get the node of the image to change
img = document.getElementsByTagName('IMG')[0];
setInterval(function(){
//what time is now
var now = new Date().getTime();
if(now - start > 60000){
//initialize the counter
start = now;
//overlay with 0's -> substr(-4)
//rotate on 1440 with a modulo -> i++ % 1440
img.src = ('000' + (i++ % 1440 + 1)).substr(-4) + '.jpg';
}
}, 10000); //check every 10 sec
</script>
If you start with Javascript a good reference is MDC
If you want to do this tied to the computer clock. Use the setInterval with a delay less than a second (<1000) and check the actual time with Date(). This way you can make your changes according to the clock.

Detecting changes to system time in JavaScript

How can I write a script to detect when a user changes their system time in JS?
There is no (portable) way to track a variable in JavaScript. Also, date information does not lie in the DOM, so you don't get the possibility of a DOM event being triggered.
The best you can do is to use setInterval to check periodically (every second?). Example:
function timeChanged(delta) {
// Whatever
}
setInterval(function timeChecker() {
var oldTime = timeChecker.oldTime || new Date(),
newTime = new Date(),
timeDiff = newTime - oldTime;
timeChecker.oldTime = newTime;
if (Math.abs(timeDiff) >= 5000) { // Five second leniency
timeChanged(timeDiff);
}
}, 500);
Check in an interval function that the time has not changed too much:
function getTime() {
var d = new Date();
return d.getTime();
}
function checkTime() {
if (Math.abs(getTime() - oldtime) > 2000) { // Changed by more than 2 seconds?
alert("You changed the time!");
}
oldtime = getTime();
}
var oldtime = getTime();
setInterval(checkTime, 1000); // Check every second that the time is not off
Tested on Windows with Opera & FF and works flawlessly.
Don't think there is a solution to what you are asking for but you can get the users timezone offset.
new Date().getTimezoneOffset() * -1
This returns the offset in minutes from GMT. Bare in mind though this does not take DST into consideration.
var last_time = new Date().getTime();
setInterval(function() {
var time = new Date().getTime();
var offset = time - last_time;
if(offset < 0 || offset > 1500) {
// Time has been changed
}
last_time = time;
}, 1000);
In theory, this should work. It will check every second to make sure the time hasn't been changed. Note that I use 1100 milliseconds as most JS interpreters don't fire off events at exactly the time specified.
Hope this helps!
use performance.now() to get duration, which will be independent of system clock
see https://developer.mozilla.org/en-US/docs/Web/API/Performance/now
var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
And then you can compare performance.now() elapsed with Date.now() elapsed to see whether they are diff too much.
Do you mean if they are changing their own system time to something that is wrong? You can ask the user for their time zone and get the correct time from the server, and then compare it to the user's system time.
You could check every 30 seconds, etc. If the new Time is off by more than 30 seconds +/- some threshold, you could do a more exhaustive comparison to determine how much it has been changed.

Categories

Resources