Search code examples
javascriptdom-events

Fire additional action *after* default?


I've read through a number of similar question on Stack Overflow, e.g., Is there a [universal] way to invoke a default action after calling event.preventDefault()?, however in this case I do not wish to to prevent the default event, but rather run some additional code as a callback once that default event has started.

Is this possible? A colleague uses a timeout with a value 1, surmising that on the current event loop, the default event will be started run, and on the next loop, the timed event will run. What do you think of this?


Solution

  • If you want to run code after the default event is finished, then setTimeout is the way to go.

    setTimeout(function(){}, 0)
    

    The value of 0ms should push this function to the bottom of the stack, so it'll be ran after the event is done.

    Have a look at this answer for a better explanation: https://stackoverflow.com/a/779785/206403