Question

I am creating an image slider for a WordPress site. It works only partialy, it presents the "show" and "hide" behaviour as expected but it does not switch the "background-image" CSS property of a div.

Links to images are in an array, a variable counter switches between all indexes of that array. Using "alert()" I was able to determine that it works perfectly well (all actions are performed correctly), but appears to bee working much too fast and causing an overflow. I am not sure if it performs actions in a correct order every time it runs though. Could you help me please?

That is the error I got from the console:

Uncaught RangeError: Maximum call stack size exceeded

And this is my code for the slider:

jQuery( document ).ready(function($) {
    var imgArray = [];
    imgArray.push("url(/projekty/sklep/wp-content/themes/maxshop/images/rotate/drugi.jpg)");
    imgArray.push("url(/projekty/sklep/wp-content/themes/maxshop/images/rotate/trzeci.jpg)");
    imgArray.push("url(/projekty/sklep/wp-content/themes/maxshop/images/rotate/czwarty.jpg)");
    imgArray.push("url(/projekty/sklep/wp-content/themes/maxshop/images/rotate/piaty.jpg)");
    var i = 0;
    myWay(imgArray, i);


    function myWay(theArray, number) {
        $('#left-title-bar').show(500).delay(7000);
        $('#left-title-bar').css("background",""+ theArray[number] + "");
        $('#left-title-bar').hide(500);
        if (number==3) {
            number = 0;
        } else {
            number = number+1;
        }
        myWay(theArray, number);
    }
});
Was it helpful?

Solution

your problem is that you use recursion without a condition to terminate , in your case you shouldn't be using recursion at all try using setInterval(functionName, milliseconds) instead. setInterval will call functionName once every milliseconds

function myWay() { // make n and theArray in the outer scope of the function
    $('#left-title-bar').hide(500,function (){
        $('#left-title-bar').css("background",""+ theArray[number] + "");
        $('#left-title-bar').show(500);
        if (number==3) {
           number = 0;
        } else {
            number = number+1;
        }

    }); //delay will not pause the code
}
setInterval(myway,2000) //will run myway once each 2 seconds 

Edit : wait for the picture to change before changing it

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top