Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript, wait for something to be true then run action

Tags:

javascript

Well the title kindof says what I need. Because in Javascript timeouts asynchronous I need to know when something becomes true. I don't want busyloop.

Came up with:

function do_when(predicate, action, timeout_step) {
    if (predicate()) {
        action();
    } else {
        setTimeout(do_when, timeout_step, predicate, action, timeout_step);
    }
}

Is it good Javascript or can I make better?

like image 418
zaharpopov Avatar asked Feb 19 '10 13:02

zaharpopov


People also ask

How do you wait for a function to complete?

Wait for function to finish using async/await keywords As you already know from the Promise explanation above, you need to chain the call to the function that returns a Promise using then/catch functions. The await keyword allows you to wait until the Promise object is resolved or rejected: await first(); second();

How do you wait for async to finish JavaScript?

The await operator is used to wait for a Promise. It can be used inside an Async block only. The keyword Await makes JavaScript wait until the promise returns a result. It has to be noted that it only makes the async function block wait and not the whole program execution.


1 Answers

Depending on what the predicate is, you might be able to fit your problem into an implementation of the observer pattern. A while back I wrote a blog post about creating JavaScript objects with observable properties. It really depends on what the predicate is, but this might get you most of the way there with code like this:

var observable = createObservable({ propToWatch: false });
observable.observe('propToWatch', function (oldValue, newValue) { 
    alert('propToWatch has changed from ' + oldValue + ' to ' + newValue); 
});
observable.propToWatch(true); // alert pops

Of course, this might be overkill for your example. Since it's never listed out explicitly (n.b. I am not a very good blogger), here's the complete code needed to make this work:

var createMediator = function () {
    var events = {};
    return {
        subscribe: function (eventName, callback) {
            events[eventName] = events[eventName] || [];
            events[eventName].push(callback);
        },
        publish: function (eventName) {
            var i, callbacks = events[eventName], args;
            if (callbacks) {
                args = Array.prototype.slice.call(arguments, 1);
                for (i = 0; i < callbacks.length; i++) {
                    callbacks[i].apply(null, args);
                }
            }
        }
    };
};

var createObservable = function (properties) {
    var notifier = createMediator(), createObservableProperty, observable;
    createObservableProperty = function (propName, value) {
        return function (newValue) {
            var oldValue;
            if (typeof newValue !== 'undefined' &&
                value !== newValue) {
                oldValue = value;
                value = newValue;
                notifier.publish(propName, oldValue, value);
            }
            return value;
        };
    };
    observable = {
        register: function (propName, value) {
            this[propName] = createObservableProperty(propName, value);
            this.observableProperties.push(propName);
        },
        observe: function (propName, observer) {
            notifier.subscribe(propName, observer);
        },
        observableProperties: []
    };
    for (propName in properties) {
        observable.register(propName, properties[propName]);
    }
    return observable;
};

My observable objects make use internally of a small eventing framework (the createMediator function) I wrote once for a project. (Before realizing jQuery supported custom events. D'oh!) Again, this may or may not be overkill for your need, but I thought it was a fun hack. Enjoy!

like image 200
Sean Devlin Avatar answered Sep 22 '22 03:09

Sean Devlin