Change background-image after specified time - javascript

I'm very new to javascript, so apologies that I haven't even attempted this as I have no clue how to even begin.
I have 3 images. Image1 is a png file, and Image2 and Image 3 are animated gifs.
What I need is very specific however. I would like Image1 to change to Image 2 after x seconds, and then change to Image3 after y seconds. Once Image3 is loaded I would like that gif to remain as the page background.
Any help would be much appreciated...
Okay so this is what I have at the moment,
var delay1 = 104000;
var delay2 = 14000;
setBackground('Image1.png');
setTimeout(function() {
setBackground('Image2.gif');
setTimeout(function() {
setBackground('Image3.gif');
}, delay2);
}, delay1);
function setBackground(src) {
image.style.backgroundImage = 'url('Image1.png + Image2.gif + Image3.gif')';
}
When run, no background image loads at all. Sorry if i'm being a complete moron. Like I said, i'm new to javascript...

You are looking for setTimeout function. It accepts two arguments: function and delay (ms), function will be called after delay.
var delay1 = 2000; // 2 seconds
var delay2 = 3000; // 3 seconds
setBackground('image-1.png');
setTimeout(function() {
setBackground('image-2.gif');
setTimeout(function() {
setBackground('image-3.gif');
}, delay2);
}, delay1);
function setBackground(src) {
image.style.backgroundImage = 'url(' + src + ')';
}

Related

How to show multiple images subsequently with a specific time delay in javascript

How I can make it work accurately so that each picture is exactly shown 50ms after the last one? (And so that the calculated time between seeing the picture and clicking is accurate?)
Background
I want to have a slideshow of images. The images are stored in the images directory and their names are sequential. The slideshow should start after the user clicks on the play button. And the user will click on the stop button a little after the 100th picture. And the code will show the user how many milliseconds after seeing the 100th picture they have clicked on the stop button. The problem is that when I run the code it doesn't work so accurate. It has some lag on some pictures. I was wondering
Here is my code:
<!DOCTYPE html>
<html>
<head>
<script>
var player;
var timestamp;
function preloadImage()
{
var i = 1
while(true){
var img = new Image();
img.src="images/" + i;
i = i + 1;
if (img.height == 0) { break; }
}
}
function next(){
var fullPath=document.getElementById("image").src;
var filename = fullPath.split("/").pop();
var n=parseInt(filename, 10) + 1;
document.getElementById("image").src = "images/" + n;
if (document.getElementById("image").height == 0) { clearInterval(player); }
if (n == 100) { timestamp = new Date().getTime(); }
}
function start(){
clearInterval(player);
document.getElementById("image").src = "images/1";
player = setInterval(function(){ next(); }, 50)
}
function stop(){
clearInterval(player);
alert("You clicked after " + (new Date().getTime() - timestamp) + "ms.")
}
preloadImage()
</script>
</head>
<body>
<img src="images/0" id="image"><br/>
<button type="button" onclick='start()'>start</button>
<button type="button" onclick='stop()'>stop</button>
</body>
</html>
As I stated in my comment, I believe your preloadImage() is not working as you expect. Try running the stack snippet below as a demonstration, and possibly make sure your cache is cleared:
function badPreloadImage () {
var img = new Image();
img.onload = function () {
// check it asynchronously
console.log('good', this.height);
};
img.src = 'https://www.w3schools.com/w3css/img_lights.jpg';
// don't check height synchronously
console.log('bad', img.height);
}
badPreloadImage();
To preload all your images properly, you must do so asynchronously:
function preloadImage (done, i) {
if (!i) { i = 1; }
var img = new Image();
img.onloadend = function () {
if (this.height == 0) { return done(); }
preloadImage(done, i + 1);
};
img.src = "images/" + i;
}
// usage
preloadImage(function () { console.log('images loaded'); });
Other concerns
You should consider using performance.now() instead of new Date().getTime(), as it uses a more precise time resolution (currently 20us, as pointed out in this comment).
You might also consider storing references to each image as an array of Image objects, rather than loading each frame via specifying the src property of an HTMLImageElement, so that the browser can just load the data from memory, rather than loading from cache on the hard drive, or even making a new HTTP request when caching is not enabled.
Addressing each of these issues will allow you to measure timing more precisely by using the proper API and eliminating lag spikes on the DOM thread due to inefficient animation.

How to preload images during a looped array for background images

I've written a simple loop that cycles through a series of images in an array into the background-image property of an element. The problem is that due to the fact that the images are loading, the animation is going haywire when everything is initially loading. I'm trying to set up a preloading workflow where:
the entire loop is blocked by waiting until the first image is fully loaded
every time a new image is fully preloaded, it begins preloading the following image
the preloading must stop when the array is over and use cached images so it's easy on the browser and doesnt just keep loading the same array on images over and over eternally.
Any help?
http://codepen.io/jeremypbeasley/pen/JoZzyo?editors=001
var photoSet = [
"https://farm6.staticflickr.com/5475/9790841974_182a06590a_o.jpg",
"https://farm3.staticflickr.com/2840/9042399407_bf04388aca_o.jpg",
"https://farm6.staticflickr.com/5504/14634417581_626ea1a835_o.jpg"
];
var p = photoSet.length;
console.log(p);
var i = 1;
function loopPhotos() {
setTimeout(function() {
$('div').css({'background-image': 'url(' + photoSet[i] + ')',});
i++;
console.log(i);
// call the next indexed image and begin to preload it
var img = new Image();
img.src = photoSet[i];
if (i >= p) {
i = 0;
// stop preloading images, somehow used images that are cached so the browser isn't working eternally reloading the same X number of photos.
}
loopPhotos();
}, 2000)
}
$(document).ready(function() {
// load first image
var firstImg = new Image();
firstImg.src = photoSet[0];
// when first image is loaded, apply it to background and begin looping
if (firstImg.complete) {
$('div').css({'background-image': 'url(' + firstImg.src + ')',});
loopPhotos();
console.log('first image loaded!');
}
});
This will do it
var photoSet = [
"https://farm6.staticflickr.com/5475/9790841974_182a06590a_o.jpg",
"https://farm3.staticflickr.com/2840/9042399407_bf04388aca_o.jpg",
"https://farm6.staticflickr.com/5504/14634417581_626ea1a835_o.jpg"
];
function preloadImageAndAct(src, action){
var img = new Image();
img.onload = action;
img.src = src;
}
function showImage( src ){
$('div').css({
'background-image': 'url(' + src + ')',
opacity: 1
});
}
var nextImage = 0;
function loopPhotos() {
console.log('Preload and show image #', nextImage);
var nextSrc = photoSet[nextImage];
preloadImageAndAct( nextSrc, function(){
showImage( nextSrc );
setTimeout( function() {
nextImage++;
nextImage %= photoSet.length;
loopPhotos();
}, 2000);
});
}
$(document).ready(function() {
loopPhotos();
});
Demo at http://codepen.io/gpetrioli/pen/rarPay
Keep in mind that you cannot transition the background-image. If you want transition for the change of images you need to either use two elements or fade the element out / change src / fade the element in.
AS for the caching, once they have been loaded once they are automatically cached by the browser so there should be no issue with that.

Jquery to let my banner images load first before it animates

I have created a banner image slideshow in jquery. Actually I just found the code somewhere, I can't remember. It starts to animate even the banner images are not yet fully loaded that makes the banner slideshow animates it's image description without images.
Anyone? please help me to modify the code and let it run by allowing the background images load first before it runs the slideshow animation.
Thank you.
(function ($) {
// Original JavaScript code.
var currentBackground = 0;
var backgrounds = [];
backgrounds[0] = 'http://www.site.com/sites/all/themes/layoutph/images/bg01.jpg';
backgrounds[1] = 'http://www.site.com/sites/all/themes/layoutph/images/bg02.jpg';
backgrounds[2] = 'http://www.site.com/sites/all/themes/layoutph/images/bg03.jpg';
backgrounds[3] = 'http://www.site.com/sites/all/themes/layoutph/images/bg04.jpg';
var customtitle = [];
customtitle[0] = "Welcome to Site";
customtitle[1] = "Site joined force with Site Foundation";
customtitle[2] = "Site Foundation school campaigns for 2014";
customtitle[3] = "New York visited by Site Foundation";
function changeBackground() {
if(currentBackground > 3 ) currentBackground = 0;
currentBackground++;
$('.masterbg').fadeOut(1000,function() {
$('div.slogan').text( customtitle[currentBackground] );
$('.masterbg').css({
'background-image' : "url('" + backgrounds[currentBackground] + "')"
});
$('.masterbg').fadeIn(1000);
});
setTimeout(changeBackground, 4000);
}
setTimeout(changeBackground, 4000);
})(jQuery);
var UserimageObj = new Image();
UserimageObj.src = "someimg.jpg";
//load the user image before doing anything
UserimageObj.onload = function () {
//do your stuff here
};
Is this what you were looking for?

Delay image loading with JavaScript

i currently need to load 123,543 images from my server but every image must go through a PHP script to generate it, the problem is that my server is very weak and it crashes after loading about 600 images, so i'm asking for a Javascript that will load 2 images / second, if possible.
Thank you.
You can use http://www.appelsiini.net/projects/lazyload
$(function() {
$("img.lazy").lazyload({
event : "sporty"
});
});
$(window).bind("load", function() {
var timeout = setTimeout(function() { $("img.lazy").trigger("sporty") }, 5000);
});
Assuming you want to place all the images in a container with id 'container', this code does the trick:
var images = [
'image1.jpg',
'image2.jpg'
],
container = document.getElementById('container');
function loadNextImage(index) {
var index = index || 0,
imageUrl = images[index],
image = document.createElement('img');
image.src = imageUrl;
container.appendChild(image);
if (index + 1 < images.length) {
setTimeout(function(){loadNextImage(index + 1)}, 500);
}
}
loadNextImage();

How do I test the time images take to load using a javascript loop

I am trying to perform some tests to see how long different images take to return to my browser. I am using a javascript for loop. However, The loop seems to run before the first image is loaded and the return does not give an accurate answer. Below is my code:
for (var radius=1; radius<10; radius++)
{
var startTime = new Date().getTime();
var img = new Image();
img.onload = function() {
var loadtime = new Date().getTime() - startTime;
console.log("image with radius: "+radius+" took " + loadtime + "ms to load");
};
url="http://test"+radius+"test2.com";
img.src = url;
}
As a result, I get:
image with radius: 10 took 175ms to load
image with radius: 10 took 368ms to load
image with radius: 10 took 463ms to load
image with radius: 10 took 608ms to load
image with radius: 10 took 751ms to load
image with radius: 10 took 895ms to load
image with radius: 10 took 1038ms to load
image with radius: 10 took 1181ms to load
image with radius: 10 took 1324ms to load
I tried different methods of trying to get the loop to run only after each image is loaded without any success. Any ideas? Thanks!
You need to put the radius and the startTime variables in a closure, otherwise you will always refer to the same variable:
function getLoadhandler(starttime, logmsg) {
return function() {
// get the local variables
console.log(logmsg+": "+(starttime-Date.now()));
};
}
for (var radius=1; radius<10; radius++) {
var img = new Image();
img.onload = getLoadhandler(Date.now(), "Load time of image with radius "+radius);
img.src = "http://test"+radius+"test2.com";
}

Categories