Question regarding setTimeout

Why does the second setTimeout callback run before the transitionstart event handler?

I would keep clicking that blue box (like a lot) and looking at the console output. Is your question ever false?

Also, just wondering, what is the reason for this little experiment? Is there a particular problem you are trying to solve?


Just want to understand why it works differently than I thought it would. Conceptual question. I explained in the comments at the top of the code the sequence I thought the code should follow.

Does transitionstart ever run before the second setTimeout? How about before the first setTimeout? If you don’t want to do a lot of clicking then I will just tell you that the transitionstart event can indeed occur before one or even both of the timeout callbacks. That’s why I wanted you to experiment with clicking, to see that there is no guarantee as to when the transitionstart callback will be executed.

I’m not 100% sure I understand what you think should happen, so I’ll just give a general answer.

Whenever you are dealing with asynchronous events there is no guarantee when they will be executed. So if order of execution is important then it is up to you to make sure that the order occurs correctly. For example, if you always want the second setTimeout to be executed after the transitionstart event then one way to do it would be to put that setTimeout inside the transitionstart callback.

OK, I read through your comments and basically you are making some assumptions that aren’t true. The time between when you toggle the ‘rotate’ class and when the transitionstart event is fired is not always going to be the same every time you click the box, there is going to be a (variable) delay between when you toggle the class and when that causes the transitionstart event to fire. Meanwhile, the code will continue to execute, running the setTimeouts. One or both of the setTimeouts could indeed beat the transitionstart event, or the transitionstart event could beat them both. Again, there are no timing guarantees when dealing with asynchronous events.

1 Like

I see. I solved it using a promise. Thanks.