Question

I have a simple script:

var bannerNum = 2;
window.setInterval(function () {
    bannerSwap(bannerNum);
}, 5000);

function bannerSwap(bannerNum) {
    if (bannerNum == 5) {
        bannerNum = 1;
        document.getElementById('b1').style.display = "block";
        document.getElementById('b4').style.display = "none";
        return;
    }
    document.getElementById('b' + (bannerNum - 1)).style.display = "none";
    document.getElementById('b' + bannerNum).style.display = "block";
    bannerNum++;
    return;
}

It just loops through the function every 5 seconds and swaps the banner image (4 divs, all display:none except the first, named b1 through b4). Pulling the page up, it switches the first time (bannerNum = 3), but it never switches after that. I alerted bannerNum at the end and saw that it switched from 2 to 3 and then it popped up every 5 seconds saying it was 3 over and over. So why isn't it incrementing?

Was it helpful?

Solution

Try

window.setInterval(function () {
    bannerSwap(bannerNum++);
}, 5000);

Remove the bannerNum++ inside the bannerSwap function

EDIT

Your code doesn't work because you are not modifying the actual bannerNum variable, but rather a parameter you recieve with the same name.

For your code to work entirely, you should do one of the following,

  • Make all the modifications to bannerNum inside the setInterval function
  • Remove the parameter from the bannerSwap signature, so you gain scope of the global variable

OTHER TIPS

As said in the comments, remove bannerNum from bannerSwap's parameter list like this:

<script>
var bannerNum = 2;
window.setInterval(function() {
    bannerSwap();
},5000);
function bannerSwap() {
    // Your code here (it will work)
}
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top