البرمجة

تصرف جافا سكريبت بشكل متزامن

JavaScript behaves synchronously when executing native code (non-async operations) like loops or other CPU-intensive tasks. This is because JavaScript is single-threaded, meaning it can only execute one piece of code at a time on a single thread. When you run a loop or other synchronous operation, JavaScript will execute it in order, blocking other code from running until the operation completes.

In your example, the for loop in the first function is a synchronous operation that blocks the execution of other code until it completes. That’s why you see ‘first’ printed before ‘second’.

However, when JavaScript interacts with asynchronous operations like making a web API call or using setTimeout, it can delegate those operations to the browser’s Web API, which runs in the background and allows JavaScript to continue executing other code while it waits for the asynchronous operation to complete. When the operation is finished, a callback function is placed in the event queue, and JavaScript will execute it when it’s done with the current synchronous code.

So, in summary, JavaScript is inherently asynchronous, but it can behave synchronously when executing certain types of native code that block the event loop.

المزيد من المعلومات

بالتأكيد! في جافا سكريبت، عندما يتعامل الكود مع العمليات التي تتطلب وقتاً للإنتهاء مثل القراءة من ملف أو الاتصال بقاعدة بيانات، يتم استخدام مفهوم المهام الغير متزامنة (Asynchronous Tasks) باستخدام مفهوم الـCallbacks أو Promises أو async/await في ES6+ للتعامل مع هذه العمليات بطريقة تسمح بمواصلة تنفيذ باقي الكود دون انتظار إنتهاء العملية.

على العكس من ذلك، عندما يتعامل الكود مع العمليات التي لا تتطلب وقتاً طويلاً مثل الحسابات البسيطة أو تعديل قيم متغيرات، يتم تنفيذها بشكلٍ متزامنٍ (Synchronously)، وذلك يعني أن الكود سينتظر حتى انتهاء تنفيذ العملية الحالية قبل تنفيذ العملية التالية.

في المثال الذي ذكرته، الحلقة التكرارية (for loop) تعتبر عملية متزامنة تستغرق وقتاً طويلاً لإنهاء التنفيذ، ولذلك يتم تنفيذ الكود بشكل تتابعي (Sequentially) حيث يتم طباعة ‘first’ ثم ‘second’.

زر الذهاب إلى الأعلى