Search code examples
javascriptjqueryajaxpollingajax-polling

AJAX Reload Interval (Polling) Assistance


I have several files I'm pulling minor text from (a single word most), and then stylizing that with another script.

Currently they load and display as they should. However, the text files update at random times, so I'd like them to be reloaded, and the subsequent script applied to them again. I've tried different setTimeout as well as setInterval commands, but I think the issue is my placement or use. After several hours of research I'm certain it's just the syntax that's out of place.

This runs locally but is pulled through a program that excecutes the script as if remote. (no cross domain issues)

Here's one example segment that pulls a file and loads to the html the subsequent script reads to display:

$(function follow_pull() {
        $.ajax({
            url : "most_recent_follower.txt",
            dataType: "text",
            success : function (data) {
                $("#follow").append(data).serialize();
            },
            setTimeout(fuction(){
                follow_pull()
            }, 10000);
        });
}); 

Here's the segment that loads those files into the script to display:

$(window).ready(function ledload() {
var options = {
        pixelSize: 5, 
        stepDelay: 62, 
        horizontalPixelsCount:650,
        verticalPixelsCount:5,
        pixelRatio: 0.8,
        pathToPixelImage: 'ticker/pixel.png',
        backgroundColor: '#000',
        disabledPixelColor : '#020202',
        enabledPixelColor: '#ff522b'
    };
    $('.canvasld, .crl').leddisplay($.extend(options, {pixelSize: 3}));
        },
            setTimeout(fuction(){
                ledload()
            }, 10000););    

Any direction is appreciated. I can post the entire file if need by, but I figured someone would get what I'm doing and know how to direct me best.

For context I'm using a script that takes the text, and makes it look like an LED and scrolls as if it's a ticker. This is being used for a broadcaster on Twitch.


Solution

  • So reviewing what you provided in your comment, I found a way to get it working. First, is the html below. Here are the differences:

    • I created a new element <div class="led"></div>. I also gave the .crl css to that element, and instead made .crl have display: none. This is because the .leddisplay function takes the element and replaces it with it's own HTML to render the LEDs. So you need to keep the div you are using to store your info separate from the div you are using to render it. (I would recommend just using JS variables to store that info, but I'm not trying to rewrite your code, just trying to get it working.)
    • But then how do you get the text into the LED display? With .leddisplay you can input the text you want as the second parameter of the function. You can see how I did that in postload().
    • To update your info, you were using append(). This adds to the divs, but you want to update them, so I replaced every .append() with .text() to replace the text rather than add on to it.
    • Finally, the heart of the solution. The leddisplay plugin doesn't have a way to update the led. So you have to 'destroy' it, and then rerun it, as I have done in the setTimeout() of postload(). But by itself, starts the scrolling all over again every 10 seconds. So what I do is track the current position, then after rerunning it, I resume the scrolling from there. However to make that work, I needed to update the plugin code. Below the HTML is the explanation for that.

    HTML:

    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    </head>
    <style>
    .led {
    padding-top: 2px;
    padding-bottom: 2px;
    background-color: #444; 
    }
    .crl {
        display: none;
    }
    </style>
    <div class="top-bar"></div>
    <div class="crl">Newest Subscriber - <span id="sub"></span>    
    LAST DONATION - <span id="donation"></span>    
    LATEST BITS - <span id="bits"></span>    
    rECENT FOLLOWEr - <span id="follow"></span>    
    Sub Goal - <span id="subgoal"></span> / 80</div>
    <div class="led"></div>
    <div class="bottom-bar"></div>
    
    <script type="text/javascript">
    $.ajaxSetup({
      async: false,
      cache: false
     });
    $(function follow_pull() {
            $.ajax({
                url : "most_recent_follower.txt",
                dataType: "text",
                success : function (data) {
                console.log(data);          
                    $("#follow").text(data);
                setTimeout(function(){
                follow_pull()
                }, 10000);
            },
        });
    }); 
    $(function donator_pull() { 
            $.ajax({
                url : "most_recent_donator.txt",
                dataType: "text",
                success : function (data) {
                console.log(data);          
                    $("#donation").text(data);
                setTimeout(function(){
                donator_pull()
                }, 10000);
            },
        });
    }); 
    $(function cheerer_pull() {     
            $.ajax({
                url : "most_recent_cheerer.txt",
                dataType: "text",
                success : function (data) {
                console.log(data);          
                    $("#bits").text(data);
                setTimeout(function(){
                cheerer_pull()
                }, 10000);
            },
        });
    }); 
    $(function subscriber_pull() {  
            $.ajax({
                url : "most_recent_subscriber.txt",
                dataType: "text",
                success : function (data) {
                console.log(data);          
                $("#sub").text(data);
                setTimeout(function(){
                subscriber_pull()
                }, 10000);
            },
        });
    }); 
    $(function count_pull() {       
            $.ajax({
                url : "total_subscriber_count.txt",
                dataType: "text",
                success : function (data) {
                console.log(data);
                    $("#subgoal").text(data);
               setTimeout(function(){
                count_pull()
                }, 10000);
            },
        });
    }); 
    $(function ledload() {
    $.getScript( "ticker/jquery.leddisplay.js", function( data, textStatus, jqxhr ) {
      console.log( data ); // Data returned
      console.log( textStatus ); // Success
      console.log( jqxhr.status ); // 200
      console.log( "Load was performed." );
        }); 
    });
    $(function postload() {
        var options = {
                pixelSize: 5, 
                stepDelay: 62, 
                horizontalPixelsCount:650,
                verticalPixelsCount:5,
                pixelRatio: 0.8,
                pathToPixelImage: 'ticker/pixel.png',
                backgroundColor: '#000',
                disabledPixelColor : '#020202',
                enabledPixelColor: '#ff522b'
            };
            $(".led").leddisplay($.extend(options, {
                pixelSize: 3
            }), $('.crl').text());
    
            setTimeout(function () {
                //get the current position
                var x = $(".led").leddisplay('getCurrentPosition')
    
                //destroy the led setup
                $('.led').leddisplay('destroy');
    
                //create it again
                postload();
    
                //set the position to where it left off at
                $(".led").leddisplay('setCurrentPosition', x)
            }, 10000);
    });
    </script>
    

    Inside the plugin, look for customMethods towards the bottom. I added 2 more methods to it: getCurrentPosition and setCurrentPosition, so it should look like this:

    jquery.leddisplay.js, customMethods:

    var customMethods = {
        init: function(){
            var _arg = arguments;
            return this.each(function() {
                var $this = $(this);
                if ($this.data('leddisplay'))
                    return;
    
                $this.data('leddisplay', true);
                var methods = resolveMethods(this);
                methods.init.apply($this, _arg);
            });
        },
        destroy: function(){
            var _arg = arguments;
            return this.each(function() {
                var $this = $(this);
                if (!$this.data('leddisplay'))
                    return;
    
                $this.data('leddisplay', null);
                var methods = resolveMethods(this);
                methods.destroy.apply($this, _arg);
            });
        },
        start: function(){
    
        },
        stop: function(){
    
        },
        getCurrentPosition: function(){
            return $(this).data('currentPosition');
        },
        setCurrentPosition: function(x){
            $(this).data('currentPosition', x);
        }
    }
    

    After you make these changes, it should work as expected.