Run function immediately then run after specified time - javascript

function imgMan(){
var frames = 6;
var img = document.getElementsByClassName('img-man')[0];
var frame = 1;
var animation = setInterval(function() {
if (frame == frames) {
clearInterval(animation); return;
}
img.style.background = 'url(images/img-man-'+ frame++ + '.png) no-repeat';
}, 140);
}
This will run the function after 140ms that is each image would be changed after 140ms. But I need to run the function immediately and after then changing image should be after 140ms.
How can I do that?
I'm having currently this:
after 140ms img-man-1 after 140ms img-man-2 after 140ms img-man-3 and like so
But I need this:
after 0ms img-man-1 after 140ms img-man-2 after 140ms img-man-3 and like so

Just store it in a variable, and evoke it manually
function imgMan(){
var frames = 6;
var img = document.getElementsByClassName('img-man')[0];
var frame = 1;
var func = function() {
if (frame == frames) { clearInterval(animation); return; }
img.style.background = 'url(images/img-man-'+ frame++ + '.png) no-repeat';
};
var animation = setInterval(func, 140);
setTimeout(func, 0);
}

Related

How to create a screensaver in javascript

I want to create a screensaver in JavaScript but I don't know how can I set the time between the images,.
I have an Ajax call and I see if the time is, for example, 2s or 90s, but I don't know how to set that time between images, this is my code:
var cont = 0;
var time = 1000
setInterval(function() {
console.log(tiempo);
if(cont == imagenes.length){
return cont = 0;
}else{
var imagen = imagenes[cont].imagen;
$('#imgZona').attr('src', imagen);
var time = imagenes[cont].tiempoVisible;
finalTime = Number(time);
}
cont++;
}, Number(finalTime ));
but the time between images is always the same, 1000, how can I change it for the time that I receive in the Ajax call? Which is imagenes[cont].tiempoVisible
I cannot comment as I don't have enough reputation, but take a look at this fiddle
https://jsfiddle.net/kidino/4mbpR/
var mousetimeout;
var screensaver_active = false;
var idletime = 5;
function show_screensaver(){
$('#screensaver').fadeIn();
screensaver_active = true;
screensaver_animation();
}
function stop_screensaver(){
$('#screensaver').fadeOut();
screensaver_active = false;
}
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
$(document).mousemove(function(){
clearTimeout(mousetimeout);
if (screensaver_active) {
stop_screensaver();
}
mousetimeout = setTimeout(function(){
show_screensaver();
}, 1000 * idletime); // 5 secs
});
function screensaver_animation(){
if (screensaver_active) {
$('#screensaver').animate(
{backgroundColor: getRandomColor()},
400,
screensaver_animation);
}
}
It will change background-color on idle mouse for 5 seconds, you can replace the code to change image, instead of background color.
Control set every timeout on each iteration.
var cont = 0;
var time = 1000
function next () {
console.log(tiempo);
if(cont == imagenes.length){
cont = 0;
}
var imagen = imagenes[cont].imagen;
$('#imgZona').attr('src', imagen);
cont++;
setTimeout(next, Number(imagenes[cont].tiempoVisible));
}
setTimeout(next, Number(initialTime));
Also I fixed a frindge condition.

Javascript Frame Animation Flashing on Load

Here is the CodePen of the animation. It flashes for the first cycle of the frames displayed. Is there a way to stop this from happening?
Any help would be very much appreciated!
let frames = [
"http://i.imgur.com/QhvQuaG.png",
"http://i.imgur.com/VjSpZfB.png",
"http://i.imgur.com/Ar1czX0.png",
"http://i.imgur.com/ROfhCv4.png",
"http://i.imgur.com/6B32vk7.png",
"http://i.imgur.com/2t5MWOL.png",
"http://i.imgur.com/a9wLBbc.png",
"http://i.imgur.com/OBKcW8f.png",
"http://i.imgur.com/RC6wLgw.png",
"http://i.imgur.com/2HyI8yS.png"];
let startframe = 0;
function arrow(){
let start = Date.now();
let timer = setInterval(function() {
let timePassed = Date.now() - start;
if (timePassed >= 20000) {
clearInterval(timer); // finish the animation after 2 seconds
return;
}
move();
}, 200);
}
function move(){
if (startframe==(frames.length-1)){
startframe=0;
} else {
startframe++;
}
// document.getElementById('continue').style.backgroundSize = "100%";
document.getElementById('continue').style.background = "url(" + frames[startframe] +")";
document.getElementById('continue').style.backgroundSize = "100%";
}
#continue {
width: 80px;
height:40px;
}
<div onclick = "arrow()">Start</div>
<div id="continue"></div>
If you look at the network tab of your browser dev tools, you'll see that the flashing happens when the browser is loading the images.
You should preload all the images before starting the animation, like so:
let frames = [
"http://i.imgur.com/QhvQuaG.png",
"http://i.imgur.com/VjSpZfB.png",
"http://i.imgur.com/Ar1czX0.png",
"http://i.imgur.com/ROfhCv4.png",
"http://i.imgur.com/6B32vk7.png",
"http://i.imgur.com/2t5MWOL.png",
"http://i.imgur.com/a9wLBbc.png",
"http://i.imgur.com/OBKcW8f.png",
"http://i.imgur.com/RC6wLgw.png",
"http://i.imgur.com/2HyI8yS.png"
]
var startframe = 0
var images = [] // This array will contain all the downloaded images
function preloadImages() {
var loaded = 0
for (i = 0; i < frames.length; i++) {
images[i] = new Image();
images[i].onload = function() {
loaded += 1
if (loaded >= frames.length) {
arrow()
}
}
images[i].src = frames[i]
}
}
function arrow(){
let start = Date.now();
let timer = setInterval(function() {
let timePassed = Date.now() - start;
if (timePassed >= 20000) {
clearInterval(timer) // finish the animation after 2 seconds
return;
}
move()
}, 200)
}
function move() {
var c = document.getElementById('continue')
c.innerHTML = '' // remove the content of #continue
// Insert the already exiting image from the images array
// into the container instead of downloading again with css
c.append(images[startframe])
if (startframe >= frames.length - 1) {
startframe = 0
}
else {
startframe++
}
}
#continue {
width: 80px;
height:40px;
}
#continue > img {
max-width: 100%;
}
<div onclick = "preloadImages()">Start</div>
<div id="continue"></div>
This is because the images need to be loaded when viewed for the first time. It is possible to pre-load images in different ways. Here are three ways to preload images.

if body has class Fade in mp3 sound else fade out

I am trying to fade the volume of an mp3 in to 1 if the body has the class fp-viewing-0
How ever this isn't working and the volume doesn't change how can I fix this?
Code:
var audio0 = document.getElementById('audio-0');
audio0.volume = 0;
setInterval( function(){
if ($("body").hasClass("fp-viewing-0")) {
audio0.animate({volume: 1}, 1000);
}
else {
audio0.animate({volume: 0}, 1000);
}
}, 100);
HTML
<audio id="audio-0" src="1.mp3" autoplay="autoplay"></audio>
I've also tried:
$("#audio-0").prop("volume", 0);
setInterval( function(){
if ($("body").hasClass("fp-viewing-0")) {
$("#audio-0").animate({volume: 1}, 3000);
}
else {
$("#audio-0").animate({volume: 0}, 3000);
}
}, 100);
Kind Regards!
I have changed the jquery animate part to a fade made by hand. For that i created a fade time and steps count to manipulate the fade effect.
var audio0 = document.getElementById('audio-0');
audio0.volume = 0;
if ($("body").hasClass("fp-viewing-0")) {
audio0.volume = 1; //max volume
var fadeTime = 1500; //in milliseconds
var steps = 150; //increasing makes the fade smoother
var stepTime = fadeTime/steps;
var audioDecrement = audio0.volume/steps;
var timer = setInterval(function(){
audio0.volume -= audioDecrement; //fading out
if (audio0.volume <= 0.03){ //if its already inaudible stop it
audio0.volume = 0;
clearInterval(timer); //clearing the timer so that it doesn't keep getting called
}
}, stepTime);
}
Better would be to place all of this in a function that receives these values a fades accordingly so that it gets organized:
function fadeAudio(audio, fadeTime, steps){
audio.volume = 1; //max
steps = steps || 150; //turning steps into an optional parameter that defaults to 150
var stepTime = fadeTime/steps;
var audioDecrement = audio.volume/steps;
var timer = setInterval(function(){
audio.volume -= audioDecrement;
if (audio.volume <= 0.03){ //if its already inaudible stop it
audio.volume = 0;
clearInterval(timer);
}
}, stepTime);
}
Which would make your code a lot more compact and readable:
var audio0 = document.getElementById('audio-0');
audio0.volume = 0;
if ($("body").hasClass("fp-viewing-0")) {
fadeAudio(audio0, 1500);
}

First function triggers second

I am terrible at javascript, how do I get function 1 (fade) to call / trigger function 2 (continuity) on completion of the volume fade as set out in the first. I have found answers in JQuery how would I do this in pure JS.
Function 1:
function fade(){
"use strict";
var timepiece,
soundwaves = document.getElementsByTagName("video")[0];
if (soundwaves.volume > 0) {
soundwaves.volume -= 0.005;
timepiece = setTimeout(fade, 80);
}
}
Function 2:
<!-- Continuity: (Javascript) -->
function continuity(){
var elements = document.querySelectorAll("main")[0];
elements.style.transition = "opacity 3s linear 0s";
elements.style.opacity = 1.0;
var audiofade,
audio = document.getElementById("ambience");
if (audio.volume < 1.0) {
audio.volume += 0.005;
audiofade = setTimeout(sync, 80);
}
}
simply call second in the else block
function fade()
{
"use strict";
var timepiece,
soundwaves = document.getElementsByTagName("video")[0];
if (soundwaves.volume > 0)
{
soundwaves.volume -= 0.005;
timepiece = setTimeout(fade, 80);
}
else
{
continuity();
}
}

change an image onload

I have a simple webpage with an image in a div on the homepage and would like to use javascript to change the image for an alternative image after the page has loaded (only once) using a slow fade, i am currently using an animated gif to do this but would prefer to use javascript.
I have limited javascript skills.
thanks
I'm assuming that you won't use jQuery so i've created simple js eample which fades out one image and fades in other after page is loaded. You can check the example here http://jsfiddle.net/rJzPV/7/
function fadeOut(elem, time, callbackFn) {
var startOpacity = elem.style.opacity || 1;
elem.style.opacity = startOpacity;
(function go() {
elem.style.opacity -= startOpacity / (time / 100);
// for IE
elem.style.filter = 'alpha(opacity=' + elem.style.opacity * 100 + ')';
if (elem.style.opacity > 0.11)
setTimeout(go, 100);
else {
elem.style.display = 'none';
if (callbackFn)
callbackFn();
}
})();
}
function fadeIn(elem, time) {
var startOpacity = 0.1;
elem.style.opacity = startOpacity;
elem.style.display = "";
(function go() {
elem.style.opacity -= -startOpacity / (time / 1000);
// for IE
elem.style.filter = 'alpha(opacity=' + elem.style.opacity * 100 + ')';
if (elem.style.opacity < 1)
setTimeout(go, 100);
})();
}
window.addEvent('load', function () {
function changePicture() {
var _myImg = document.getElementById("myImage");
_myImg.src = "http://www.google.com/logos/2012/klimt12-hp.jpg";
fadeIn(_myImg, 1000);
}
var _myImg = document.getElementById("myImage");
fadeOut(_myImg, 1000, changePicture);
});

Categories

Resources