How can I reuse a function properly? - javascript

I try to make 3 basic slideshow.
I made this code for the first one and wanted to use it on the other 2 as well with the New slideS() method and with some parameter changing.But it's not working,even the first function is'nt working if I put parameter in it.
Can somebody explain me why is this not working and how to fix it?Thanks beforehand!
var img = document.getElementById("asd");
var imgArr = ["1.jpg", "3.png", "3.png"];
var i = 0;
function slideS(a) {
a.src = imgArr[i];
if (i < imgArr.length - 1) {
i++;
} else {
i = 0;
}
setTimeout("slideS()", 1500);
}
slideS(img)

You could do something like this, using an object oriented approach:
function SlideShow(el, imagesArray, msDelay) {
this.el = el;
this.images = imagesArray;
this.delay = (msDelay) ? msDelay : 1000;
this.timer = null;
this.Run = function () {
var self = this;
var index = 0;
this.timer = setInterval(function(){
self.el.src = self.images[index++ % self.images.length];
}, this.delay);
}
this.Stop = function() {
this.timer = null;
}
}
var img = document.getElementById("asd");
var imgArr = ["1.jpg", "3.png", "3.png"];
var delay = 1500;
var ss = new SlideShow(img, imgArr, delay);
ss.Run();
...
ss.Stop();
Would that work for you? Then you are using pure functions and an object that can be used to start, stop, and manage any slide show.

I think you want like:
Remove setTimeout. And use setInterval:
setInterval(function(){
slideS(img)
},1500)

You could use a closure over the element and the array and use setInterval instead of setTimeout.
function slide(id, array) {
function swap() {
image.src = array[i];
i++;
i %= array.length;
}
var image = document.getElementById(id),
i = 0;
setInterval(swap, 1500);
}
slide('image1', ['http://lorempixel.com/400/200/', 'http://lorempixel.com/400/200/', 'http://lorempixel.com/400/200/']);
<image id="image1"></image>

I assume it works when the function doesn't take a parameter?
Then, the reason it would work with no parameter, but stop working with a parameter, is that the setTimeout tries to recursively call the function but doesn't pass a parameter. So you'd change that to
setTimeout(() => {slideS(a);}, 1500);
But then when you try to run multiple instances of this concurrently, you'll get into trouble because your'e using global variables. You'll need to use something more local (perhaps closures?) for your lcv, for example.

try this... you are making mistake at some places
var img = document.getElementById("asd");
var imgArr = ["1.jpg", "3.png", "3.png"];
var i = 0;
function slideS(a) {
a.src = imgArr[i];
if (i < imgArr.length - 1) {
i++;
} else {
i = 0;
}
setTimeout(() => slideS(a), 1500);
/* you need to pass function to setTimeout and pass refrence of image that's 'a' */
// or use function instead of arrow function
setTimeout(function() { slides(a) }, 1500);
}
slideS(img)
hope this helps..

You have to use setInterval instead of setTimeout
var img = document.getElementById("asd");
var imgArr = ["https://i.stack.imgur.com/lgt0W.png", "https://i.stack.imgur.com/X0fKm.png", "https://i.stack.imgur.com/YfPSD.png"];
var i = 0;
function slideS(a) {
a.src = imgArr[i];
if (i < imgArr.length - 1) {
i++;
} else {
i = 0;
}
}
slideS(img); //initial call to start it without having to wait for 1500 ms to pass
setInterval(function() {
slideS(img);
}, 1500);
<img id="asd">

Related

Having real trouble combining 2 JS

I am struggling combining two JS into one… I try and try in the JSFiddle but can not really understand the console erros…
I am trying to have a background-color that changes combined with a changing background .svg in a div…
$(document).ready(function() {
//Initializing
var i = 0;
var images = []; //array
var time = 3000; // time in millie seconds
//images
images[0] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_1.svg)";
images[1] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_2.svg)";
images[2] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_3.svg)";
images[3] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_4.svg)";
//function
function changeImage() {
var el = document.getElementById('header');
el.style.backgroundImage = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
setTimeout('changeImage()', time);
}
window.onload = changeImage;
$(function setbackground() {
window.setTimeout( "setbackground()", 2000);
var index = Math.round(Math.random() * 4);
var ColorValue = "FA89CB";
if(index == 1)
ColorValue = "FAED96";
if(index == 2)
ColorValue = "D27DFA";
if(index == 3)
ColorValue = "6CFA64";
if(index == 4)
ColorValue = "8370FA";
document.getElementsByTagName("body")[0].style.backgroundColor = "#" + ColorValue;
});
});
Here's my fiddle:
http://jsfiddle.net/gmck02ru/1/
does somebody have a clue – i guess I am not really understanding what I am doing here so far...
Help please!
The issue is because the syntax you've used to define the setbackground() function is incorrect. You've placed it inside a jQuery object. That function is also never called. You should define it as a standalone function and invoke it when the page loads.
In addition there's a few improvements you can make to the logic.
Use addEventListener() over setting the onclick or other onX event properties.
Declare the elements of the array at the same time as you define the array itself.
Use an array to hold the background colours instead of hard-coding an if statement.
Use the modulo operator when incrementing the counter to save having to write logic to reset to 0
If you want to repeatedly update the background colour, as you do for the images, place the setTimeout() call within the setbackground() function.
Use document.body directly instead of getting it by tag name
$(document).ready(function() {
let i = 0;
let images = [
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_1.svg)",
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_2.svg)",
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_3.svg)",
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_4.svg)"
];
let backgroundColours = ['#FAED96', '#D27DFA', '#6CFA64', '#8370FA']
function changeImage() {
let el = document.getElementById('header');
el.style.backgroundImage = images[i];
i = ++i % (images.length - 1)
setTimeout(changeImage, 3000);
}
changeImage();
function setbackground() {
let index = Math.round(Math.random() * 4);
document.body.style.backgroundColor = backgroundColours[index];
setTimeout(setbackground, 2000);
}
setbackground();
});
Working jsFiddle - see the demo in the fiddle as the images are on an insecure domain so cannot be called from SO.

Confused about SetInterval and closures

How can we repeatedly update the contents of a div using setInterval
I am using the question from this link as a reference How to repeatedly update the contents of a <div> by only using JavaScript?
but i have got few questions here
Can we do it without anonymous functions,using closures. I have tried but could not end up with any workable solution.
How can we make it run infinitely, with the following code it gets stopped once i reaches 10.
window.onload = function() {
var timing = document.getElementById("timer");
var i = 0;
var interval = setInterval(function() {
timing.innerHTML = i++;
if (i > 10) {
clearInterval(interval);
i = 0;
return;
}
}, 1000);
}
<div id="timer"></div>
I am confused about setIntervals and closures
can some one help me here
Thanks
You could do something like this with a closure. Just reset your i value so, you will always be within your given range.
window.onload = function() {
var updateContent = (function(idx) {
return function() {
if (idx === 10) {
idx = 0;
}
var timing = document.getElementById("timer");
timing.innerHTML = idx++;
}
})(0);
var interval = setInterval(updateContent, 1000);
}
<div id="timer"></div>
This one should be clearer.
function updateTimer() {
var timer = document.getElementById("timer");
var timerValue = parseInt(timer.getAttribute("data-timer-value")) + 1;
if (timerValue == 10) {
timerValue = 0;
}
timer.setAttribute("data-timer-value", timerValue);
timer.innerHTML = "the time is " + timerValue;
}
window.onload = function() {
setInterval(updateTimer, 1000);
}
<div id="timer" data-timer-value="0"></div>

Change img src every second using Jquery and Javascript

I have been trying to write a script that changes an image src every two seconds based on a list.
So, everything is inside a forloop that loops over that list:
$(document).ready(function() {
var lis = {{dias|safe}}; <----- a long list from django. This part of the code works fine.
for (i=0; i<lis.length; i++){
src_img = lis[i][1];
var timeout = setInterval(function(){
console.log(src_img)
$("#imagen").attr("src", src_img);
}, 2000)
}
});
It doesn't work, the console logs thousands of srcs that correspond to the last item on the list. Thanks a lot for your help.
you don't need to run cycle in this case, you just save "pointer" - curentImage and call next array item through function ever 2 sec
var curentImage = 0;
function getNextImg(){
var url = lis[curentImage];
if(lis[curentImage]){
curentImage++;
} else {
curentImage = 0;
}
return url;
}
var timeout = setInterval(function(){
$("#imagen").attr("src", getNextImg());
}, 2000)
var curentImage = 0;
var length = lis.length;
function NewImage(){
var url = lis[curentImage];
if(curentImage < length){
currentImage++;
}
else{
currentImage = 0;
}
return url;
}
var timeout = setInterval(function(){
$("#imagen").attr("src", getNextImg());
}, 2000)
PS: Better than the previous one, Checks for lis length and starts from first if you reach end.
You need something like this
$(document).ready(function() {
var index = 0;
setInterval(function(){
src_img = lis[index++ % lis.lenght][1]; // avoid arrayOutOfBounds
$("#imagen").attr("src", src_img);
}, 2000)
});

Creating a delay in for-loop iterations

I've written the following function with hopes to add 1px onto the top margin to animate a window sliding out of the page.
Currently it works fine and removes the window from the page, However I'm having problems creating the delay interval in each iteration of the for loop. I've thought about using setTimeout(), but with this I cant just break; the for loop I have to call a function,
Any ideas?
function slideOut() {
var obj = document.getElementById("cInstructs");
var orig = 66;
for(i=0; i<2000; i++) {
orig++;
obj.style.marginTop = orig+"px";
}
};
Thanks in advance!
A suggestion would be to check the jQuery .slideDown() function- http://api.jquery.com/slideDown/
var i;
function incrAndDelay(i) {
setTimeout(...);
i+=1;
return i;
}
function slideOut() {
var obj = document.getElementById("cInstructs");
var orig = 66;
for(i=0; i<2000; incrAndDelay(i)) {
orig++;
obj.style.marginTop = orig+"px";
}
};
Still have to call a function but not in the loop body.
var intId;
function slideOut() {
clearInterval(intId);
var count = 0;
var obj = document.getElementById("cInstructs");
var orig = 66;
intId = setInterval(function(){
orig++;
obj.style.marginTop = orig+"px";
if((++count == 2000)){
clearInterval(intId);
}
}, 100);
}

Setting a time for flicker animation on img

I'm using this code to make my logo flicker on my website. But It becomes annoying when it continues to flicker while browsing, how can I set a time to allow it to flicker for something like the first 15seconds on page load, then stops?
JS code I'm using:
$(document).ready(
function(){
var t;
const fparam = 100;
const uparam = 100;
window.flickr = function(){
if(Math.round(Math.random())){
$("#logodcoi").css("visibility","hidden");
t = setTimeout('window.unflickr()',uparam);
}
else
t = setTimeout('window.flickr()',fparam);
}
window.unflickr = function(){
if(Math.round(Math.random())){
$("#logodcoi").css("visibility","visible");
t = setTimeout('window.flickr()',fparam);
}
else
t = setTimeout('window.unflickr()',uparam);
}
t = setTimeout('window.flickr()',fparam);
});
You could have a counter, which you then use to decide whether you want to set another timeout. As a side note, you should never add functions to window and then passing a string to setTimeout. Always just pass the function itself:
$(document).ready(function(){
var t;
var amount = 0;
const fparam = 100;
const uparam = 100;
function timeout(f, t) { // this function delegates setTimeout
if(amount++ < 150) { // and checks the amount already (un)flickered
setTimeout(f, t); // (150 * 100 ms = 15 s)
}
}
var flickr = function(){
if(Math.round(Math.random())){
$("#logodcoi").css("visibility","hidden");
t = timeout(unflickr,uparam);
}
else
t = timeout(flickr,fparam);
};
var unflickr = function(){
if(Math.round(Math.random())){
$("#logodcoi").css("visibility","visible");
t = timeout(flickr,fparam);
}
else
t = timeout(unflickr,uparam);
};
t = timeout(flickr,fparam);
});
I see you're using jquery, you could use the following, if I remember correctly, all the stuff I use below has been in jquery since 1.0, so you should be good:
counter = 1;
function hideOrShow(){
$(".classToSelect").animate({"opacity": "toggle"}, 100);
counter = counter +1;
if (counter >= 21) clearInterval(flickerInterval);
}
flickerInterval = setInterval(hideOrShow, 100);
Change the selector, animation duration, and variable names to whatever you fancy/need.

Categories

Resources