0

I have a small library with a single API function, start().

Once started, it should check a URL every 2 seconds and after some time the url-checker will resolve.

But I don't know how to implement the repeated setTimeout for a deferred function..I tried variations where the checkProgress() calls itself but then the promise isn't returned anymore.

Here's the code:

Lib.progressChecker = (function($) {
    'use strict';

    var api = {};

    var checkProgress = function (url) {
        var d = $.Deferred();

        $.get(url).done(function(foo) {

            if (foo === 'bar') {
                //script is not finished yet
            } else {
                //finished, resolve and stop looping
                d.resolve();
            }
        });

        return d.promise();
    };

    api.start = function(projectId) {

        var url = 'foobar/'+projectId;

        var d = $.Deferred();

        setTimeout(function(){
            checkProgress(url).done(function () {
                d.resolve();
            });
        }, 2000);

        return d.promise();

    };

    return api;

}) (jQuery);
Oli
  • 2,370
  • 2
  • 26
  • 42

1 Answers1

0

You can do it like this where you just resolve the first deferred when you see the $.get() returns the desired value and if not, you run it again:

Lib.progressChecker = (function($) {
    'use strict';

    var api = {};
    api.start = function(projectId) {

        var url = 'foobar/'+projectId;
        var d = $.Deferred();

        function next() {
            setTimeout(function(){
                $.get(url).then(function(foo) {
                    if (foo === 'bar') {
                        // continue checking
                        next();
                    } else {
                        // done now
                        d.resolve(foo);
                    }
                }, function(err) {
                    // error so stop
                    // don't want to forever loop in an error condition
                    d.reject(err);
                });
            }, 2000);
        }

        next();
        return d.promise();
    };
    return api;

}) (jQuery);

FYI, if you control the server end of things here, it looks like an ideal situation for a webSocket where, rather than polling every two seconds, you can tell the server you want to be notified when things change and the server can just tell you when something changes on the server side.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • thanks..my backend is PHP, could I use something like Ratchet? – Oli Jan 27 '15 at 16:23
  • 1
    @Oli - yes, you could use Ratchet for webSockets with PHP. I'd personally prefer to use socket.io in the client so you'd want something compatible with that on the back-end. Some options are described [here](http://stackoverflow.com/questions/6398887/using-php-with-socket-io). The one I see mentioned the most is [elephant.io](http://elephant.io/). – jfriend00 Jan 27 '15 at 21:16