How Can I Reuse A Function Properly?
Solution 1:
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.
Solution 2:
I think you want like:
Remove setTimeout. And use setInterval:
setInterval(function(){
slideS(img)
},1500)
Solution 3:
You could use a closure over the element and the array and use setInterval
instead of setTimeout
.
functionslide(id, array) {
functionswap() {
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/']);
<imageid="image1"></image>
Solution 4:
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.
Solution 5:
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;
functionslideS(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 functionsetTimeout(function() { slides(a) }, 1500);
}
slideS(img)
hope this helps..
Post a Comment for "How Can I Reuse A Function Properly?"