Jonathon Oates
Jonathon Oates

Reputation: 2952

Execute the code but delay the 'return' of a function in JS

Am I able to, and if so how, delay the return of a Javascript function?

For example, say I use JS to set the background of an element that employs CSS3's transitions, and that transition takes 1 second, I'd like to return the function after the transition has finished (after 1 second).

Something like this (pseudo code):

function
    element.style = 'background: #aaa; transition: all 1s ease-in;' // this will take 1 second to transition, although the JS is executed immediately

    after 1 second // delay the return until the CSS3 transition completes.
        return element

I hope this all makes sense! Thank you in advance, your help is much appreciated!

It might be helpful for everyone to see the actual code too: http://jsfiddle.net/BtNSs/1/

Upvotes: 2

Views: 4584

Answers (3)

Tomalak
Tomalak

Reputation: 338248

You do not want to delay the return. You want to execute a callback after one second.

function (element) {
    element.style = 'background: #aaa; transition: all 1s ease-in;' 

    setTimeout(function () {
      // whatever you wanted to do with the element;
    }, 1000);
}

Ideally, as @AndyE points out, you don't do it "after one second", but when the transitionend event occurs. This is more flexible and generally the right thing to do. Cross-browser support for that event is not yet soild, though. Depending on what you want to achieve, "after one second" might be a lot easier to implement.

Upvotes: 0

Jamiec
Jamiec

Reputation: 136124

How about supplying a callback to the function, and executing that callback after the required amount of time.

function doSomething(callback){
  // execute your transition

  setTimeout(callback,1000);
}

Live example: http://jsfiddle.net/eAMXK/ - you'll see it output the current time to the console, then a second later do the same.

Upvotes: 0

Andy E
Andy E

Reputation: 344595

No, you're not able to do this. In browsers, JavaScript and the UI share the same thread, so the animation will not begin until your JavaScript code finishes executing.

If you want to do something after the animation completes, use the transitionend event.

Upvotes: 4

Related Questions