I need to create some animation using DHTML/Javascript and I am struggling to get anything I do to work. My parameters are it must use the setInterval function, a user defined function and 8 jpg files. There must also be a way of stopping the animation.
If someone could get me pointed in the right direction I would be very happy. I have not been able to find suitable information on how to do this so far and I am still fairly new to Javascript. Thanks.
Sorry for not posting code earlier. It was such a mess I didn't want to embarrass myself. Here's what I have. It's not working.
var slideShow = ['images/pic0.jpg','images/pic1.jpg','images/pic2.jpg','images/pic3.jpg','images/pic4.jpg','images/pic5.jpg','images/pic6.jpg','images/pic7.jpg'];
picO = new Array();
for(i=0; i < slideShow.length; i++) {
picO[i] = new Image();
picO[i].src = slideShow[i];
}
var curPic = -1;
function changeImage(){
curPic = (++curPic > slideShow.length-1)? 0 : curPic;
imgO.src = picO[curPic].src;
setInterval(changeImage,100);
}
window.onload=function(){
imgO = document.getElementById("imgAnim");
changeImage();
}
var t=setTimeout(function(){alert("Welcome to my animated page")},3000)
The other thing it needs to do is pop up an alert box 3 seconds after the animation starts. It's doing that but it's popping up EVERY 3 seconds, which is not what I want.
Thanks for your help so far. I've done pretty well with my Javascript work lately but this one is just something I'm not that familiar with.
To the using of setInterval and stopping the animation
var animation = setInterval(yourAnimation,500); // run yourAnimation every 500ms
clearInterval(animation); // stop animation
To the animation
var slideShow = ["img1.jpg","img2.jpg", ... ,"img8.jpg"];
var counter = 0;
function yourAnimation() {someImage.src = slideShow[++counter%slideShow.length];}
Related
I have a simple question maybe, I was for days looking for solution and don't want to waste your time, but isn't work for me so I'm here now.
Im using P5JS, and I wanted to create auto click function.
There how I call an button in sketch.js file
var button1 = createButton("Generator");
button1.mousePressed(banana);
button1.id('autoclick');
Here you can see how I call in index.html
Im trying something like this:
<script type="text/javascript">
var iteration = true;
var time = new Date();
var delay = 5000; // 5 secondes
while(iteration) {
if(time.getTime() + 5000 < new Date().getTime()) {
iteration = false;
}
}
document.getElementByID('autoclick').click();
// noprotect
</script>
Maybe I complicate to much? any suggetions? thank you!
Your while loop is blocking, which means that while Javascript is running your while loop, it will not be able to execute any other code. You want to use setInterval() for your purposes.
For example,
setInterval(() => console.log("hello!"), 1000)
I have some images that I am displaying through JSON. This file refreshes the content every 10 seconds so the new images added show without a page refresh.
I am struggling to add a slideshow code without the two refresh's clashing with each other.
I would really appreciate some help.
This is my current code.
function update_content() {
$.getJSON("showImages.php", function(data) {
$("#slides").html(
data.result.map(({image1}) => `<img class="slides" src="data:image/png;base64,${image1}" />`).join("")
);
setTimeout(update_content, 10000);
var index = 0;
slideshow();
function slideshow() {
var i;
var x = document.getElementsByClassName("slides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
index++;
if (index > x.length) {index = 1}
x[index-1].style.display = "block";
setTimeout(slideshow, 20000);
}
})
}
$(function() {
update_content()
})
The way this is written, there's no way the refreshes wouldn't clash with each other and cause a large mess in updating. What you have here will, every 10 seconds, do a ping back to the server for some json and then spawn what is essentially a thread (not in the technical sense, but in the behavior sense) that every 20 seconds hides all the slides and shows the first slide. By about 60 seconds into this page running, you now have six instances of the slideshow() function queued to run, the newly created one trying to show the first slide, the next most recently created two showing the second, the next two showing the third, etc. And because network lag is unpredictable, they'll all fire at slightly different times in an unpredictable order.
The main problem is setTimeout(slideshow, 20000). It's not needed as this is currently written. Slideshow() is being run every 10 seconds already from the outer function running every 10; it doesn't need to run separately in its own timeout. And if you're running it at that interval already, the slideshow function is useless anyway, and the server only needs to return one image in its json, and the whole slideshow function can be deleted.
Though I question why you need to do a network round-trip every 10 seconds to begin with. Unless this is some real-time snapshot of a camera feed or something, you can easily just give javascript a large array of images for it to cycle through and maybe do the server ping for new images every 10 minutes or so instead. If you go this route, instead move slideshow() out of the update_content() function and just call it once from the jquery onready function to set it running and leave it be. If you need to call slideshow() in the getJson callback, be sure to cancelTimeout on the previous setTimeout(slideshow, ...)'s return value, so you don't make pseudo-threads as described above.
I have searched extensively to find a solution to this but have not succeeded.
I have created a 4 second video clip that loops seamlessly in an editor.
However when the clip runs in a page via Safari, Chrome or Firefox there is a small but noticeable pause in the playback from end back to beginning.
I have tried using the loop and preload attributes both together and independently.
I have also tried the following javascript:
loopVid.play();
loopVid.addEventListener("timeupdate", function() {
if (loopVid.currentTime >= 4) {
loopVid.currentTime = 0;
loopVid.play();
}
}
But in all cases the momentary pause remains and spoils the effect.
I'm open to any ideas?
Since this question is a top search result in Google, but doesn't "technically" have an answer yet, I'd like to contribute my solution, which works, but has a drawback. Also, fair warning: my answer uses jQuery.
It seems the slight pause in the video loop is because it takes time for html5 video to seek from one position to another. So it won't help anything to try to tell the video to jump to the beginning when it ends, because the seek will still happen. So here's my idea:
Use javascript to clone the tag, and have the clone sit hidden, paused, and at the beginning. Something like this:
var $video = $("video");
var $clone = $video.clone();
$video.after($clone);
var video = $video[0];
var clone = $clone[0];
clone.hidden = true;
clone.pause();
clone.currentTime = 0;
Yes, I used clone.hidden = true instead of $clone.hide(). Sorry.
Anyway, after this the idea is to detect when the original video ends, and then switch to the clone and play it. That way there is only a change in the DOM as to which video is being shown, but there is actually no seeking that has to happen until after the clone starts playing. So after you hide the original video and play the clone, you seek the original back to the beginning and pause it. And then you add the same functionality to the clone so that it switches to the original video when it's done, etc. Just flip flopping back and forth.
Example:
video.ontimeupdate = function() {
if (video.currentTime >= video.duration - .5) {
clone.play();
video.hidden = true;
clone.hidden = false;
video.pause();
video.currentTime = 0;
}
}
clone.ontimeupdate = function() {
if (clone.currentTime >= clone.duration - .5) {
video.play();
clone.hidden = true;
video.hidden = false;
clone.pause();
clone.currentTime = 0;
}
}
The reason I add the - .5 is because in my experience, currentTime never actually reaches the same value as duration for a video object. It gets pretty close, but never quite there. In my case I can afford to chop half a second off the end, but in your case you might want to tailor that .5 value to be as small as possible while still working.
So here's my entire code that I have on my page:
!function($){
$(document).ready(function() {
$("video").each(function($index) {
var $video = $(this);
var $clone = $video.clone();
$video.after($clone);
var video = $video[0];
var clone = $clone[0];
clone.hidden = true;
clone.pause();
clone.currentTime = 0;
video.ontimeupdate = function() {
if (video.currentTime >= video.duration - .5) {
clone.play();
video.hidden = true;
clone.hidden = false;
video.pause();
video.currentTime = 0;
}
}
clone.ontimeupdate = function() {
if (clone.currentTime >= clone.duration - .5) {
video.play();
clone.hidden = true;
video.hidden = false;
clone.pause();
clone.currentTime = 0;
}
}
});
});
}(jQuery);
I hope this will be useful for somebody. It works really well for my application. The drawback is that .5, so if someone comes up with a better way to detect exactly when the video ends, please comment and I will edit this answer.
I've found that Firefox will stutter while looping if I'm using mp4 or ogv files. I changed the code in my page to try using a webm file first instead, and suddenly the stutter was gone and the video looped seamlessly, or at least close enough that I didn't see an issue. If you haven't given that a shot, it could be worth it to try converting the file to a webm format and loading that instead.
okay So I'm trying to leverage the video.js project as it's seems pretty amazing!
anyways, im writing my first script that interacts with the api which can be found below. it's basically just supposed to output the current play time to the div current_time , the id of video tag is my_stream anyways here's all my javascript ... the problem im having is playLength=0 and current time never updates when video is playing and remains at 0 (ie. is never more then 0 ) im not sure what im doing wrong here ... the api rules i followed can also be found here video.js api docs
function current_time(){
_V_("my_stream").ready(function(){
var myPlayer = this;
// EXAMPLE:
var playLength = myPlayer.duration();
do
{
var position = myPlayer.currentTime();
var myTextArea = document.getElementById('time_count');
myTextArea.innerHTML = position;
}
while(position < playLength);
});
}
window.onload = current_time
anyhelp from any one who's implemented anything with the api or just see something dumb i've done would be greatly appreciated, thanks!
You're assigning the duration to playLength before playback begins. If that's zero when you assign it, it will remain zero. Check the note in the API doc "NOTE: The video must have started loading before the duration can be known, and in the case of Flash, may not be known until the video starts playing."
It looks like you're only concerned about the duration to work out when the video is playing. It would be far better just to use the timeupdate event instead.
var myPlayer;
var myTextArea = document.getElementById('time_count');
videojs('my_stream').ready(function(){
myPlayer = this;
myPlayer.addEvent('timeupdate', onProgress);
});
function onProgress() {
myTextArea.innerHTML = myPlayer.currentTime();
}
This should execute after the DOM has loaded (with window.onload, or jQuery's $(document).ready()), or go in a script tag in the body after the video and #time_count elements.
I Have sort-of solved this problem bymyself by modifying the code I Had written so it now works like so
function current_time(){
_V_("my_stream").ready(function(){
var myPlayer = this;
var playLength = myPlayer.duration();
var position = myPlayer.currentTime();
var myTextArea = document.getElementById('time_count');
myTextArea.innerHTML = position + "/" + playLength;
t=setTimeout(function() {current_time()},2000);
});
}
... although it seems stupid to poll duration continuosly, I actually don't need this value going forward in development, however both populate properly now once the video is playing so it's kinda a solution. I'm not going to except my own answer right away to see if anyone can solve this a better way, or if you can explain why video.js changes the id tag and how to properly deal with it i'll give you an up vote and accept your answer if it all makes sense to me.
I have started learning javascript a couple of days ago and done the codeacadmey stuff and thought i will try make a simple game.
so i came up with the memory game where you have to find pairs of images.
it is all working and i got a score system in place but a few people have said the delay that happens once the cards have been chosen to allowing another chocie is hindering them and i cant figure out how to improve that performance.
here is a bit of code i think is causing the delay, is there any better way to produce the same result, sorry about before i am new to all this.
function check() {
clearInterval(tid);
if(people[secondchocie] === people[firstchocie]) {
cntr++;
(cntr === numOfMatches) {
stop();
score = checkScore(amountGoes);
$('#gameFinished').append('<p>Well done, you managed to complete the game your score is <span>' + score + '</span></p>');
}
turns = 0;
return;
} else {
document.images[firstchocie + numOfImages].src = backcard;
document.images[secondchocie + numOfImages].src = backcard;
turns = 0;
return;
}
}
I can't create comments, so I'll put this in an answer.
Although I agree with lukas.pukenis ...
Changing images can take some time if they aren't preloaded. To test this: Try to get them into the browser cache by adding them somewhere else in the page (i.e. with an IMG tag) before starting the game.
Then you'll be sure they are in the cache.
edit:
I recently used this:
var cache = [];
function preLoadImages(arrImg)
{
var args_len = arrImg.length;
for (var i = args_len; i--;)
{
var cacheImage = document.createElement('img');
cacheImage.src = arrImg[i];
cache.push(cacheImage);
}
}
preLoadImages(['images/img1.png','images/img2.png','images/img3.png',]);
you can add all images needed to the javascript array.
If your a quick study :) you can do the following:
If your page is generated by php you could let php read the entire images directory and write the filenames in the page as javascript code.
Or you could create an ajax request wich returns all paths to the images and sends them to the preload function as a callback.