How can I run the same JavaScript function on every page rendered with jQuery Mobile?

I require assistance in revising this script. The objective is to display an array of images for a duration of 3 seconds upon loading each page. While the initial page works as intended, the images on subsequent pages are changing more rapidly than expected.

<div data-role="page" id="page1" class="ads">
 <div data-role="main" class="ui-content">
  <div class="advertisers" align="center">
      <img src="" width="100%" class="currentAd">
  </div>
 </div>
</div>

<div data-role="page" id="page2" class="ads">
 <div data-role="main" class="ui-content">
  <div class="advertisers" align="center">
      <img src="" width="100%" class="currentAd">
  </div>
 </div>
</div>

<div data-role="page" id="page3" class="ads">
 <div data-role="main" class="ui-content">
  <div class="advertisers" align="center">
      <img src="" width="100%" class="currentAd">
  </div>
 </div>
</div>

<script>
    $('.ads').on("pagecreate", function(event){

      clearInterval(imageSwitch);

        let adImage1 = localStorage.getItem("adImage1");
        let adImage2 = localStorage.getItem("adImage2");
        let adImage3 = localStorage.getItem("adImage3");

        let imagesArray = ["admin/img/marketing/" + adImage1, "admin/img/marketing/" + adImage2, "admin/img/marketing/" + adImage3];
        let currentImageIndex = 0;
        function changeImage() {
          currentImageIndex = (currentImageIndex + 1) % 3;
          $('.currentAd').attr('src', imagesArray[currentImageIndex]);
        }

       setInterval(changeImage, 3000);

    });
</script>

Hi CreatingStone,

To solve the overlapping intervals issue, ensure only one interval is active using an IIFE and clear any existing intervals on each page show. Try this simplified version:

<script>
(function() {
    let imageSwitch;
    const imagesArray = [
        "admin/img/marketing/" + localStorage.getItem("adImage1"),
        "admin/img/marketing/" + localStorage.getItem("adImage2"),
        "admin/img/marketing/" + localStorage.getItem("adImage3")
    ];
    let currentImageIndex = 0;

    function changeImage() {
        currentImageIndex = (currentImageIndex + 1) % imagesArray.length;
        $('.currentAd').attr('src', imagesArray[currentImageIndex]);
    }

    $(document).on("pageshow", ".ads", function() {
        if (imageSwitch) clearInterval(imageSwitch);
        $('.currentAd').attr('src', imagesArray[currentImageIndex]);
        imageSwitch = setInterval(changeImage, 3000);
    });
})();
</script>

This ensures only one interval is running at any time, preventing rapid changes.

Looks like your current setup restarts the interval each time a page is created, leading to multiple overlapping intervals. Try this:

<script>
    $(document).on("pagecreate", ".ads", function() {
        let adImage1 = localStorage.getItem("adImage1");
        let adImage2 = localStorage.getItem("adImage2");
        let adImage3 = localStorage.getItem("adImage3");

        let imagesArray = ["admin/img/marketing/" + adImage1, "admin/img/marketing/" + adImage2, "admin/img/marketing/" + adImage3];
        let currentImageIndex = 0;
        let imageSwitch = window.setInterval(function() {
            currentImageIndex = (currentImageIndex + 1) % imagesArray.length;
            $('.currentAd').attr('src', imagesArray[currentImageIndex]);
        }, 3000);

        $(document).on('pageshow', 'div.ads', function() {
            $('.currentAd').attr('src', imagesArray[0]);
        });
    });
</script>

This should correctly reset the image each time a page is shown, without creating extra intervals.

The issue you’re encountering is due to the overlapping intervals because each time a new page is rendered, a new interval is created without clearing the previous one. The solution provided by CreativeArtist88 is on the right track, but to ensure a consistent behavior, we can refine it further. Here’s an approach that ensures the image changes without unintended acceleration:

<script>
    (function() {
        let imageSwitch;
        const imagesArray = [
            "admin/img/marketing/" + localStorage.getItem("adImage1"),
            "admin/img/marketing/" + localStorage.getItem("adImage2"),
            "admin/img/marketing/" + localStorage.getItem("adImage3")
        ];
        let currentImageIndex = 0;
        function changeImage() {
            currentImageIndex = (currentImageIndex + 1) % imagesArray.length;
            $('.currentAd').attr('src', imagesArray[currentImageIndex]);
        }

        $(document).on("pageshow", ".ads", function() {
            if (imageSwitch) clearInterval(imageSwitch);
            $('.currentAd').attr('src', imagesArray[currentImageIndex]);
            imageSwitch = setInterval(changeImage, 3000);
        });
    })();
</script>

Key Adjustments and Explanation:

  • Wrapped Functionality in an IIFE (Immediately Invoked Function Expression): This helps encapsulate variables and avoid potential global namespace pollution.
  • Clearing Interval on pageshow Event: By setting up the interval during the pageshow event, and clearing any previous interval, it ensures only one active interval is running at a time. This eliminates the compounding effect of multiple intervals.
  • Initial Image Setting: Upon each page view, the image is reset to its correct starting position within the image array by utilizing the currentImageIndex variable.

These adjustments ensure that each page loads the images in the intended 3-second cycle without overlap issues.

Hi CreatingStone,

It seems like the main problem you're facing is multiple overlapping intervals due to them being set every time a page is created. This causes the images to change more rapidly than expected. To prevent this, we need to ensure only one interval is active at any given time. Here's a refined approach:

<script>
    (function() {
        let imageSwitch;
        const imagesArray = [
            "admin/img/marketing/" + localStorage.getItem("adImage1"),
            "admin/img/marketing/" + localStorage.getItem("adImage2"),
            "admin/img/marketing/" + localStorage.getItem("adImage3")
        ];
        let currentImageIndex = 0;

        function changeImage() {
            currentImageIndex = (currentImageIndex + 1) % imagesArray.length;
            $('.currentAd').attr('src', imagesArray[currentImageIndex]);
        }

        $(document).on("pageshow", ".ads", function() {
            if (imageSwitch) clearInterval(imageSwitch);
            $('.currentAd').attr('src', imagesArray[currentImageIndex]);
            imageSwitch = setInterval(changeImage, 3000);
        });
    })();
</script>

### Key Improvements and Explanation:

  • Single Interval Management: Uses IIFE (Immediately Invoked Function Expression) for encapsulation and manages one interval through the use of clearing previous intervals in the pageshow event handler.
  • Consistent Image Setting: On each page, sets the image initially to currentImageIndex position ensuring a consistent start.

Implementing this setup should resolve the issue by maintaining a consistent 3-second image cycling pace without any overlaps.