Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
dTub
Скачать

Understanding JavaScript Promises with setTimeout: A Deep Dive into Asynchronous Behavior

Автор: vlogize

Загружено: 2025-05-28

Просмотров: 2

Описание:

Explore the nuances of using `setTimeout` in JavaScript Promises, and learn why understanding asynchronous behavior is vital for effective coding.
---
This video is based on the question https://stackoverflow.com/q/65417021/ asked by the user 'RicardoAlvveroa' ( https://stackoverflow.com/u/14846677/ ) and on the answer https://stackoverflow.com/a/65417119/ provided by the user 'Ricki-BumbleDev' ( https://stackoverflow.com/u/5577580/ ) at 'Stack Overflow' website. Thanks to these great users and Stackexchange community for their contributions.

Visit these links for original content and any more details, such as alternate solutions, latest updates/developments on topic, comments, revision history etc. For example, the original title of the Question was: Promise running setTimeout in then asynchronously

Also, Content (except music) licensed under CC BY-SA https://meta.stackexchange.com/help/l...
The original Question post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license, and the original Answer post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license.

If anything seems off to you, please feel free to write me at vlogize [AT] gmail [DOT] com.
---
Understanding JavaScript Promises with setTimeout: A Deep Dive into Asynchronous Behavior

JavaScript's asynchronous nature can often lead to unexpected behavior, especially when working with Promises and functions like setTimeout. A common confusion arises when trying to understand why certain outputs are logged in a specific order. Let's unravel this mystery by exploring a common scenario involving promises and setTimeout.

The Problem

Consider the following code snippet written using an Immediately Invoked Function Expression (IIFE):

[[See Video to Reveal this Text or Code Snippet]]

When you run this code, the output is:

"first"

"third"

Waits 3 seconds...

"second"

The sequence might seem puzzling at first: Why does "third" appear before "second" if the setTimeout is within a then? Isn’t everything inside then run synchronously?

The Explanation

To understand the behavior, it’s crucial to grasp how JavaScript handles asynchronous operations. Here’s a breakdown of what’s happening step-by-step:

1. Logging the First Message

The IIFE is executed, and the promise starts executing.

Immediately, "first" is logged to the console because console.log("first") runs synchronously.

2. Resolving the Promise

After logging "first", the resolve() function is called, which signals that the promise’s execution is complete. This action does not wait for any further responses—execution continues immediately.

3. Moving to the Next then

Now, the .then() block is invoked. Inside this block, there’s a setTimeout() which schedules the logging of "second" after 3 seconds.

However, important to note is that setTimeout does not execute immediately—it simply schedules the operation to occur after the specified delay.

4. Logging the Final Message

After scheduling "second" with setTimeout, the execution engine proceeds to the next line of code, which is the .then() block chained to the initial promise.

Consequently, "third" is then logged to the console right away.

5. Final Output After Delay

Finally, after waiting 3 seconds, the setTimeout callback executes and logs "second".

The Correct Approach

If you want setTimeout to behave in a Promise-like manner, resolving it after the timeout, you need to create a new promise wrapped around setTimeout. Here's how you can achieve that:

[[See Video to Reveal this Text or Code Snippet]]

In Context

Integrating this logic back into your promise flow looks like this:

[[See Video to Reveal this Text or Code Snippet]]

What Happens Here?

The code first logs "first" and resolves.

Then, it creates a new promise. Inside that promise, setTimeout both logs "second" and resolves after 3 seconds.

Only after the second promise is resolved does it proceed to log "third".

Summary

Understanding how JavaScript handles asynchronous operations is crucial for effective coding. Using setTimeout within promises requires special handling to ensure the order of execution is as intended. By wrapping setTimeout in a promise, you maintain control over when your asynchronous actions are completed.

Key Takeaways:

setTimeout does not block execution; it schedules tasks for the future.

To treat setTimeout like a Promise, wrap it in a new Promise.

Always remember the asynchronous nature of JavaScript when debugging outputs.

With these insights, you're now better equipped to navigate the intricacies of asynchronous JavaScript programming. Happy coding!

Understanding JavaScript Promises with setTimeout: A Deep Dive into Asynchronous Behavior

Поделиться в:

Доступные форматы для скачивания:

Скачать видео mp4

  • Информация по загрузке:

Скачать аудио mp3

Похожие видео

array(10) { [0]=> object(stdClass)#4354 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "qWm8yJ_mDAs" ["related_video_title"]=> string(25) "10 Pro Tips for AI Coding" ["posted_time"]=> string(23) "7 часов назад" ["channelName"]=> string(11) "Volo Builds" } [1]=> object(stdClass)#4327 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "FBpgdSjJ6nQ" ["related_video_title"]=> string(27) "Immediate JSON Parsing in C" ["posted_time"]=> string(23) "5 часов назад" ["channelName"]=> string(13) "Tsoding Daily" } [2]=> object(stdClass)#4352 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "xge7nTp72yU" ["related_video_title"]=> string(72) "#11. Dynamic Memory Allocation in C | malloc, calloc, realloc & free" ["posted_time"]=> string(21) "9 дней назад" ["channelName"]=> string(8) "DevTechX" } [3]=> object(stdClass)#4359 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "MiOGJ5k8EMI" ["related_video_title"]=> string(93) "⚡️ Путин резко ответил Западу || Потеря территорий" ["posted_time"]=> string(24) "15 часов назад" ["channelName"]=> string(23) "Время Прядко" } [4]=> object(stdClass)#4338 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "h5C2PRh46Wk" ["related_video_title"]=> string(35) "Python Fundamentals VI-Conditionals" ["posted_time"]=> string(21) "5 дней назад" ["channelName"]=> string(30) "Sangeetha's Educational Videos" } [5]=> object(stdClass)#4356 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "TNWR0HXHAHg" ["related_video_title"]=> string(64) "I Tried an 'Entry Level' 𝐇𝖆𝖈𝓴𝖎𝖓𝖌 Challenge." ["posted_time"]=> string(21) "1 день назад" ["channelName"]=> string(9) "CyberFlow" } [6]=> object(stdClass)#4351 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "l4xGh6Qvikk" ["related_video_title"]=> string(44) "Making a Simple Logger Using Print in Python" ["posted_time"]=> string(22) "11 дней назад" ["channelName"]=> string(12) "Script Chimp" } [7]=> object(stdClass)#4361 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "MQ8ibs-JiRo" ["related_video_title"]=> string(102) "Заявление Путина о завершении войны / Последнее условие" ["posted_time"]=> string(24) "15 часов назад" ["channelName"]=> string(10) "NEXTA Live" } [8]=> object(stdClass)#4337 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "gkAvH0SHJaA" ["related_video_title"]=> string(127) "Большие деньги, большой риск: Как везут ценные грузы через всю Канаду!" ["posted_time"]=> string(24) "15 часов назад" ["channelName"]=> string(25) "АЛЕКС Брежнев" } [9]=> object(stdClass)#4355 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "iyrnPNBWIQ4" ["related_video_title"]=> string(161) "«Жить надо сегодня». Олег Тиньков и Майкл Калви о взлете нового финтех-стартапа Plata" ["posted_time"]=> string(19) "2 дня назад" ["channelName"]=> string(28) "Это Осетинская!" } }
10 Pro Tips for AI Coding

10 Pro Tips for AI Coding

Immediate JSON Parsing in C

Immediate JSON Parsing in C

#11. Dynamic Memory Allocation in C | malloc, calloc, realloc & free

#11. Dynamic Memory Allocation in C | malloc, calloc, realloc & free

⚡️ Путин резко ответил Западу || Потеря территорий

⚡️ Путин резко ответил Западу || Потеря территорий

Python Fundamentals VI-Conditionals

Python Fundamentals VI-Conditionals

I Tried an 'Entry Level' 𝐇𝖆𝖈𝓴𝖎𝖓𝖌 Challenge.

I Tried an 'Entry Level' 𝐇𝖆𝖈𝓴𝖎𝖓𝖌 Challenge.

Making a Simple Logger Using Print in Python

Making a Simple Logger Using Print in Python

Заявление Путина о завершении войны / Последнее условие

Заявление Путина о завершении войны / Последнее условие

Большие деньги, большой риск: Как везут ценные грузы через всю Канаду!

Большие деньги, большой риск: Как везут ценные грузы через всю Канаду!

«Жить надо сегодня». Олег Тиньков и Майкл Калви о взлете нового финтех-стартапа Plata

«Жить надо сегодня». Олег Тиньков и Майкл Калви о взлете нового финтех-стартапа Plata

© 2025 dtub. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: [email protected]