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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)