Skip to content

Using setTimeout to “win” a race condition when changing views

I’ll admit. I’ve been stressed at work. I think the spring/yearly goal-setting/”OMG ROADMAP” brouhaha got to me. I’m a people person, and I get wrapped up in what other people are dealing with, sometimes to my own detriment.

So last week when I was “cannot even” about dealing with a race condition on making sure an event happened after a repaint, I was very excited to stealth learn* something fascinating that I’m still wrapping my head around.

We were building an interaction where we needed to trigger a resize, but only after the repaint had finished. The dark horse for getting that to work? window.setTimeout:

window.setTimeout(function(){ $(window).trigger('resize'); }, 0);

For an interesting post that goes over this with some more code (read the comments as well), check this out.

Briefly, JavaScript is single-threaded, so setTimeout sort of pops your code out of the running to execute after the VM is done with other things, rather than what it usually does toggling on a single action (how it gives the illusion of things happening simultaneously).

I’m still wrapping my head around this somewhat, so if you want to share insight in the comments, please do!

* Being surprised by a trick I didn’t know. Love it when that happens!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.