Steve
Steve

Reputation: 175

Lock simultaneous JavaScript invocation

I have a simple JavaScript function that manipulates the DOM (heights of elements for layout reasons).

The function get's called on window's resize (throttled to 1s) and on button click. In my function everything is wrapped inside a _.delay() function in order for the script to wait 1s for a triggered animation to finish.

The problem is that sometimes the function get's called fast on after another and the second call starts before the first call ending. Now the function calls are doing their things simultaneously and everything get's bad.

My question:
How can I tell the function to only run one at a time? Some kind of lock would be good that locks the second call from executing. It would be great if this second call still executes, but only after the first call remove the lock.

Is something like this possible in JavaScript and how?

EDIT

Here is a code example of how the script looks like:

function doStuff() {
    var stuff = $('[data-do-stuff]');
    var height = stuff.height();

    // Add CSS class that changes height of stuff
    // Class starts an animation of duration of 1s
    stuff.addClass('active-stuff');

    // Wait 1s for the animation started by added class
    _.delay(function() {
        stuff.height(height * 42);
    }, 1000);
}

$(window).on('resize', _.throttle(function() {
    doStuff();
}, 1000));

$('.tasty-button').on('click', function() {
    doStuff();
});

This is not a working example, just a gist of what the general structure of my script is.

If I e.g. click multiple times on the tasty button (about 3x in 1s) it messes with everything. (In my real script, I have got more trigger so just disabling the button for 1 second doesn't do the trick -.-)

I would like it to behave like this: If doStuff executes, lock every call until doStuff finishes with executing and then execute the locked calls afterwards.

Upvotes: 0

Views: 63

Answers (2)

Phillip Chan
Phillip Chan

Reputation: 993

Without code examples, it's hard to suggest solutions specific to your question. However, here's some thoughts on your overall problem:

What you're experiencing is a called a "race condition" where a part of your application depends on multiple functions finishing at undetermined times.

Generally, there are two ways to handle situations like this:

1) Use callbacks. About Callbacks

2) As another user suggested, use JS promises. About JS Promises

Upvotes: 0

Vivek Pratap Singh
Vivek Pratap Singh

Reputation: 9974

PROMISES in Javascript is what you are looking for.

Upvotes: 1

Related Questions