Read more

AngularJS: How to hook to the end of a digest cycle (before the browser redraws)

Arne Hartherz
December 03, 2014Software engineer at makandra GmbH

When you run code inside a $watch expression that forces a repaint Show archive.org snapshot (e.g. by computing an element's width, or running something like element.is(':visible')) you may end up with "page flickering" or scroll offset changes.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

You can hook to the end of a digest cycle to avoid that.

The following is basically straight from the docs Show archive.org snapshot , but pretty awkward to use. Do it like this (example here is a directive):

timeout = undefined
scope.$watch ->
  clearTimeout(timeout) if timeout
  timeout = setTimeout ->
    # your code here
  true # don't trigger another digest by always returning the same value

The timeouted function will be enqueued right to the end of the current digest cycle -- you may then run code that forces a repaint without flickering and all the nasty bits.

Note that you are outside of the digest cycle, so Angular will not update any bindings.

Posted by Arne Hartherz to makandra dev (2014-12-03 19:18)