setTimeout not the same as this.async?
Asked Answered
T

1

5

Sometimes I'm coding in a wrong way my polymer 1.0 web app and stuff stops to work properly. Like setting data to some custom element and then immediately trying to read some data out of it (that depends on the data just set) (because I don't know better). Sometimes this doesn't work. Most of the time this.async will help me out, but sometimes it will not. However, setTimeout has never ever failed me in these kind of situations. Most of the time calling setTimeout without providing wait time will work just as well.

For a long time I thought that this.async(function(){...}) is the same as setTimeout(function(){...}). Because sometimes code inside this.async will fail to see changes in custom element's data while code inside setTimeout will not.

Are these two methods are implemented in different way?

Trencherman answered 24/7, 2015 at 8:56 Comment(0)
M
7

this.async adds your function to the start of the event queue, while setTimeout adds it to the end. If you use setTimeout other functions may have been executed before your function is called, causing the changes that you can see in your data.

From the documentation of this.async:

If no wait time is specified, runs tasks with microtask timing (after the current method finishes, but before the next event from the event queue is processed)

setTimeout on the other hand will add your function to the end of the queue as is described in the section "Adding Messages" of this article.

Calling setTimeout will add a message to the queue after the time passed as second argument. If there is no other message in the queue, the message is processed right away; however, if there are messages, the setTimeout message will have to wait for other messages to be processed. For that reason the second argument indicates a minimum time and not a guaranteed time

Mammal answered 24/7, 2015 at 9:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.