Home > Enterprise >  Infinite self invoking function
Infinite self invoking function

Time:11-28

I am working on a piece of code that is supposed to randomly display a view count on my site. It all works fine, except that it only runs once on page load. Its supposed to change the view count every 10 seconds after the initial first run. E.g. run this code snippet every 10 seconds after page load. I have tried multiple ways with setInterval but found that it is supposedly bad practice to use anyways after so many failed attempts?

Could you guys point me in the right direction. I have been reading posts on Stack overflow for hours and none had an answer to my issue. I have a feeling, that I am overlooking something obvious here.

document.addEventListener('page:loaded', function() { //// Page has loaded and theme assets are ready
(function() {
    var f = function() {
        document.addEventListener('DOMContentLoaded', function() {
            // Minimum view count
            var minViews = 2;
            // Maximum view count
            var maxViews = 20;
            // Text to show after the view count number
            var text = 'people are viewing this product right now.';


            // Create the new element to display on the page
            $(".view-count").get().forEach(function(entry, index, array) {
                var $viewCountElement = Math.floor(Math.random() * (maxViews - minViews)   minViews)   ' '   text;
                $(entry).html($viewCountElement);
            });

        });
    };
    window.setInterval(f, 10000); //10 sec interval
    f();
})();
});

CodePudding user response:

You may not need nested event listener. You can just call the setInterval in the call back function of DOMContentLoaded.

function elementDisplay() {
  // Minimum view count
  var minViews = 2;
  // Maximum view count
  var maxViews = 20;
  // Text to show after the view count number
  var text = 'people are viewing this product right now.';


  // Create the new element to display on the page
  $(".view-count").get().forEach(function(entry, index, array) {
    var $viewCountElement = Math.floor(Math.random() * (maxViews - minViews)   minViews)   ' '   text;
    $(entry).html($viewCountElement);
  });

}


document.addEventListener('DOMContentLoaded', function() {
  window.setInterval(elementDisplay, 10000); //10 sec interval
});

CodePudding user response:

setInterval is a browser based API, zo it should be cleaned up from the browser properly.

This is majorly for your proper implementation of setInterval. You can add your listeners, too.

FYI: jQuery.ready/DOMContentLoaded occurs when all of the HTML is ready to interact with, but often before its been rendered to the screen.

var interval;
$(document).ready(function(){
  console.log("I am initialized")
  var f = function() {
    console.log("I am called")
    // Minimum view count
    var minViews = 2;
    // Maximum view count
    var maxViews = 20;
    // Text to show after the view count number
    var text = 'people are viewing this product right now.';
    // Create the new element to display on the page
    $(".view-count").get().forEach(function(entry, index, array) {
      var $viewCountElement = Math.floor(Math.random() * (maxViews - minViews)   minViews)   ' '   text;
      $(entry).html($viewCountElement);
    });
  };
  interval = setInterval(f, 10000);

});

$(window).on("beforeunload", function() {
  // clear the interval when window closes
  return clearInterval(interval);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Note: Check the console for output

  • Related