Repeated polling

by nickkell

HTML

<script src="http://knockoutjs.com/downloads/knockout-3.0.0.debug.js"></script>
<input type="button" data-bind="click: startPolling" value="Start polling" />
<input type="button" data-bind="click: stopPolling" value="Stop polling" />
<div data-bind="foreach: results"> 
    <span data-bind="text: $data"></span>
</div>

JavaScript

var viewModel = function (serverCall) {
    var valuesFromServer = ko.observableArray([]),
        
        shouldPoll = false,

        polling = function () {
            var deferred = shouldPoll ? serverCall() : $.Deferred().reject(),
                repoll = function() { setTimeout(polling, 1000); };
            
            deferred
            .done(function (newValue) {
                valuesFromServer.push(newValue);
                repoll();
            })
            .fail(repoll);
        };

    polling();

    return {
        results: valuesFromServer,
        startPolling: function() {
            shouldPoll = true;
        },
        stopPolling: function() {
            shouldPoll = false;
        }
    };

};


ko.applyBindings(viewModel(function () {
    return $.Deferred().resolve(new Date().getTime());
}));