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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)