Understanding Asynchronous JavaScript – Learn How JavaScript Works

Understanding Asynchronous JavaScript – Learn How JavaScript Works

JavaScript is a single-threaded programming language which means only one thing can happen at a time. That is, the JavaScript engine can only process one statement at a time in a single thread.

While the single-threaded languages simplify writing code because you don’t have to worry about the concurrency issues, this also means you can’t perform long operations such as network access without blocking the main thread.

Imagine requesting some data from an API. Depending upon the situation the server might take some time to process the request while blocking the main thread making the web page unresponsive.

That’s where asynchronous JavaScript comes into play. Using asynchronous JavaScript (such as callbacks, promises, and async/await), you can perform long network requests without blocking the main thread.

While it’s not necessary that you learn all these concepts to be an awesome JavaScript developer, it’s helpful to know 🙂

So without further ado, Let’s get started 🙂

Tip: Using Bit you can turn any JS code into an API you can share, use and sync across projects and apps to build faster and reuse more code. Give it a try.


How Does Synchronous JavaScript Work?

Before we dive into asynchronous JavaScript, let’s first understand how the synchronous JavaScript code executes inside the JavaScript engine. For example:

const second = () => {
  console.log('Hello there!');
}const first = () => {
  console.log('Hi there!');
  second();
  console.log('The End');
}first();

 

To understand how the above code executes inside the JavaScript engine, we have to understand the concept of the execution context and the call stack (also known as execution stack).

Execution Context

An Execution Context is an abstract concept of an environment where the JavaScript code is evaluated and executed. Whenever any code is run in JavaScript, it’s run inside an execution context.

The function code executes inside the function execution context, and the global code executes inside the global execution context. Each function has its own execution context.

Call Stack

The call stack as its name implies is a stack with a LIFO (Last in, First out) structure, which is used to store all the execution context created during the code execution.

JavaScript has a single call stack because it’s a single-threaded programming language. The call stack has a LIFO structure which means that the items can be added or removed from the top of the stack only.

Let’s get back to the above code snippet and try to understand how the code executes inside the JavaScript engine.

const second = () => {
  console.log('Hello there!');
}const first = () => {
  console.log('Hi there!');
  second();
  console.log('The End');
}first();

 

Call Stack for the above code

So What’s Happening Here?

When this code is executed, a global execution context is created (represented by main()) and pushed to the top of the call stack. When a call to first() is encountered, it’s pushed to the top of the stack.

Next, console.log('Hi there!') is pushed to the top of the stack, when it finishes, it’s popped off from the stack. After it, we call second(), so the second() function is pushed to the top of the stack.

console.log('Hello there!') is pushed to the top of the stack and popped off the stack when it finishes. The second() function finishes, so it’s popped off the stack.

console.log(‘The End’) is pushed to the top of the stack and removed when it finishes. After it, the first() function completes, so it’s removed from the stack.

The program completes its execution at this point, so the global execution context(main()) is popped off from the stack.

How Does Asynchronous JavaScript Work?

Now that we have a basic idea about the call stack, and how the synchronous JavaScript works, let’s get back to the asynchronous JavaScript.

What is Blocking?

Let’s suppose we are doing an image processing or a network request in a synchronous way. For example:

const processImage = (image) => {
  /**
  * doing some operations on image
  **/
  console.log('Image processed');
}const networkRequest = (url) => {
  /**
  * requesting network resource
  **/
  return someData;
}const greeting = () => {
  console.log('Hello World');
}processImage(logo.jpg);
networkRequest('www.somerandomurl.com');
greeting();

 

Doing image processing and network request takes time. So when processImage() function is called, it’s going to take some time depending on the size of the image.

When the processImage() function completes, it’s removed from the stack. After that the networkRequest() function is called and pushed to the stack. Again it’s also going to take some time to finish execution.

At last when the networkRequest() function completes, greeting() function is called and since it contains only a console.log statement and console.log statements are generally fast, so the greeting() function is immediately executed and returned.

So you see, we have to wait until the function (such as processImage() or networkRequest()) has finished. This means these functions are blocking the call stack or main thread. So we can’t perform any other operation while the above code is executing which is not ideal.

So what’s the solution?

The simplest solution is asynchronous callbacks. We use asynchronous callbacks to make our code non-blocking. For example:

const networkRequest = () => {
  setTimeout(() => {
    console.log('Async Code');
  }, 2000);
};console.log('Hello World');networkRequest();

 

Here I have used setTimeout method to simulate the network request. Please keep in mind that the setTimeout is not a part of the JavaScript engine, it’s a part of something known as web APIs (in browsers) and C/C++ APIs (in node.js).

To understand how this code is executed we have to understand a few more concepts such event loop and the callback queue (also known as task queue or the message queue).

An Overview of JavaScript Runtime Environment

The event loop, the web APIs and the message queue/task queue are not part of the JavaScript engine, it’s a part of browser’s JavaScript runtime environment or Nodejs JavaScript runtime environment (in case of Nodejs). In Nodejs, the web APIs are replaced by the C/C++ APIs.

Now let’s get back to the above code and see how it’s executed in an asynchronous way.

const networkRequest = () => {
  setTimeout(() => {
    console.log('Async Code');
  }, 2000);
};console.log('Hello World');networkRequest();console.log('The End');

 

Event Loop

When the above code loads in the browser, the console.log(‘Hello World’) is pushed to the stack and popped off the stack after it’s finished. Next, a call to networkRequest() is encountered, so it’s pushed to the top of the stack.

Next setTimeout() function is called, so it’s pushed to the top of the stack. The setTimeout() has two arguments: 1) callback and 2) time in milliseconds (ms).

The setTimeout() method starts a timer of 2s in the web APIs environment. At this point, the setTimeout() has finished and it’s popped off from the stack. After it, console.log('The End') is pushed to the stack, executed and removed from the stack after its completion.

Meanwhile, the timer has expired, now the callback is pushed to the message queue. But the callback is not immediately executed, and that’s where the event loop kicks in.

The Event Loop

The job of the Event loop is to look into the call stack and determine if the call stack is empty or not. If the call stack is empty, it looks into the message queue to see if there’s any pending callback waiting to be executed.

In this case, the message queue contains one callback, and the call stack is empty at this point. So the Event loop pushes the callback to the top of the stack.

After that the console.log(‘Async Code’) is pushed to the top of the stack, executed and popped off from the stack. At this point, the callback has finished so it’s removed from the stack and the program finally finishes.

DOM Events

The Message queue also contains the callbacks from the DOM events such as click events and keyboard events. For example:

document.querySelector('.btn').addEventListener('click',(event) => {
  console.log('Button Clicked');
});

 

In case of DOM events, the event listener sits in the web APIs environment waiting for a certain event (click event in this case) to happen, and when that event happens, then the callback function is placed in the message queue waiting to be executed.

Again the event loop checks if the call stack is empty and pushes the event callback to the stack if it’s empty and the callback is executed.

We have learned how the asynchronous callbacks and DOM events are executed which uses the message queue to store all the callbacks waiting to be executed.

ES6 Job Queue/ Micro-Task queue

ES6 introduced the concept of job queue/micro-task queue which is used by Promises in JavaScript. The difference between the message queue and the job queue is that the job queue has a higher priority than the message queue, which means that promise jobs inside the job queue/ micro-task queue will be executed before the callbacks inside the message queue.

For example:

console.log('Script start');setTimeout(() => {
  console.log('setTimeout');
}, 0);new Promise((resolve, reject) => {
    resolve('Promise resolved');
  }).then(res => console.log(res))
    .catch(err => console.log(err));console.log('Script End');

Output:

Script start
Script End
Promise resolved
setTimeout

 

We can see that the promise is executed before the setTimeout, because promise response are stored inside the micro-task queue which has a higher priority than the message queue.

Let’s take another example, this time with two promises and two setTimeout. For example:

console.log('Script start');setTimeout(() => {
  console.log('setTimeout 1');
}, 0);setTimeout(() => {
  console.log('setTimeout 2');
}, 0);new Promise((resolve, reject) => {
    resolve('Promise 1 resolved');
  }).then(res => console.log(res))
    .catch(err => console.log(err));new Promise((resolve, reject) => {
    resolve('Promise 2 resolved');
  }).then(res => console.log(res))
    .catch(err => console.log(err));console.log('Script End');

This prints:

Script start
Script End
Promise 1 resolved
Promise 2 resolved
setTimeout 1
setTimeout 2

We can see that the two promises are executed before the callbacks in the setTimeout because the event loop prioritizes the tasks in micro-task queue over the tasks in message queue/task queue.

While the event loop is executing the tasks in the micro-task queue and in that time if another promise is resolved, it will be added to the end of the same micro-task queue, and it will be executed before the callbacks inside the message queue no matter for how much time the callback is waiting to be executed.

For example:

console.log('Script start');setTimeout(() => {
  console.log('setTimeout');
}, 0);new Promise((resolve, reject) => {
    resolve('Promise 1 resolved');
  }).then(res => console.log(res));new Promise((resolve, reject) => {
  resolve('Promise 2 resolved');
  }).then(res => {
       console.log(res);
       return new Promise((resolve, reject) => {
         resolve('Promise 3 resolved');
       })
     }).then(res => console.log(res));console.log('Script End');

This prints:

Script start
Script End
Promise 1 resolved
Promise 2 resolved
Promise 3 resolved
setTimeout

So all the tasks in micro-task queue will be executed before the tasks in message queue. That is, the event loop will first empty the micro-task queue before executing any callback in the message queue.

Conclusion

So we have learned how asynchronous JavaScript works and other concepts such as call stack, event loop, message queue/task queue and job queue/micro-task queue which together make the JavaScript runtime environment. While it’s not necessary that you learn all these concepts to be an awesome JavaScript developer, but it’s helpful to know these concepts 🙂

Credit @medium

[Themeforest] Appside – App Landing Page – Freebiees Free Download

[Themeforest] Appside – App Landing Page – Freebiees Free Download

Appside – App Landing Page is the perfect app showcase HTML template. Appside – App Landing Page is a better way to present your modern business… You can easily change any design. It’s easy to customize and also well documented.

 

Appside – App Landing Page html Template Features

  • 14 Homepage
  • Blog And Blog Details
  • Blog Dark And Blog Details Dark Version
  • W3C validate
  • Fully Responsive
  • Unique and Modern Style
  • Free Google Fonts
  • Super Clear and Clean Layout
  • Flexible layout system
  • Responsive design
  • Every page is fully layered and organized with proper names
  • Fully Customizable
  • Documentation included
  • Easy to find the files name, folder, layers, groups.
  • Great Support 24/7

List of html file

  • 01_Home.html
  • 02_Home.html
  • 03_Home.html
  • 04_Home.html
  • 05_Home.html
  • 06_Home.html
  • 07_Home.html
  • 08_Home.html
  • 09_Home.html
  • 10_Home.html
  • 11_Home.html
  • 12_Home.html
  • 13_Home.html
  • 14_Home.html
  • 15_Blog.html
  • 16_Blog_Details.html
  • 17_Blog_Dark.html
  • 18_Blog_Details_Dark.html

Icon:

  • FontAwesome
  • Flaticon

.

Fonts

  • Poppins

Credit:

  • Freepic
  • pexels
  • shutterstock

Note:All stock images are for preview purposes only and are not included in the download package

 

[CodeCanyon] WooCommerce Colors and Swatches for Variations

[CodeCanyon] WooCommerce Colors and Swatches for Variations

WooCommerce Colors and Swatches for Variations

This plugin provides a much nicer way to display variations of variable products.

Are you running an E-Commerce store and thus want to adorn your site with best of image swatches?

Viola… WooCommerce Color and Swatches for Variations will help you with selecting variations which will beautify and manage your estore. There you can apply product images with your woocommerce products intact which will give a the perfect picture of your swatch image.

Adding to the list, woocommerce color swatch count upon extending product attributes which will give a streamlined look of your store to your customers who are buying things from your excellent and unique platform. Woocommerce color swatch provides a beautiful a clean look that helps to attract your customers and give a real swatch image of your woocommerce product.

 

WooCommerce Colors and Swatches for Variations - 3

 

WooCommerce Colors and Swatches for Variations - 4

 

Benefits of WooCommerce Color and Swatches for Variations:

1. User friendly interface

2. Defines every selected woocommerce product with global attribute and swatch images.

3. WooCommerce Color and Swatches for Variations provides with perfect display of thumbnail display type.

4. WooCommerce Color Swatches comes with different size variation for product detail page as well as shop/archive/category page.

5. WooCommerce color swatch provides smooth color and image swatches for variable products.

WooCommerce Colors and Swatches for Variations - 5

 

WooCommerce Colors and Swatches for Variations - 6

 

WooCommerce Colors and Swatches for Variations - 7

 

Live Demo

Visit demos to experience the unmatched benefits of plugin and explore the settings.

Frontend demo : Click here
Backend demo : Click here

 

This plugin is not subjected to GDPR compliant as it does not store any sensitive data of a user. It only holds information related to software which is run by WordPress & WooCommerce of the holder.

Thank-you for your interest in WooCommerce Colors And Swatches For Variations, Makewebbetter.

 

The Freebies you download from this site is 100% legal, we collect them from promotions from world’s seller websites, credit back to source is always available below this message (if you want to support author, please purchase their products to get recently updates.)
Laptop And Mobile Screen MockUp – PSD Template – Freebies Free Download

Laptop And Mobile Screen MockUp – PSD Template – Freebies Free Download

Laptop & Mobile Screen Mock-Up -PSD Template
It is Super Easy to Use/Edit/Customize
these files with Smart Object.
Just Place in, your own Images.

Screenshot

Features

  • Files Included:
  • File Types:Photoshop CC 2015(PSD)
    Size:
  • Mobile Screen 857x1537px
  • Laptop Screen 2642x1739px
  • 1 Psd File.
  • 300 DPI
  • Easy to Customize
  • Photoshop CC 2015 & Higher Version

Requirements

  • Photoshop CC 2015

Instructions

Note:*This is a Mock-up File

 

Codecaynon Laravel 6.0 Vue.js SPA Bootstrap Admin Starter Kit – Freebies Download

Codecaynon Laravel 6.0 Vue.js SPA Bootstrap Admin Starter Kit – Freebies Download

What is Laravel 6.0 Vue.js SPA Admin Starter Kit?

 

Laravel 6.0 Vue.js SPA Bootstrap Admin Starter Kit

Live Preview Screenshot

 

This project also uses jQuery in it.

Login Details

Admin User: [email protected]/password

Staff User: [email protected]/password

EVERYTHING WHICH YOU NEED TO START A LARAVEL PROJECT!

Laravel is the most popular PHP framework since since its inception. Vue.js is new but its gaining lots of attention from all over the world since last 2 year. You can generate some awesome apps by combining Laravel & Vue.js.

There are many Laravel+Vue.js starter kit available but none of them are complete enough to get started. Some lacks with basic functionality like authentication, some with sample CRUD module, some with responsive layout etc. I tried to create one starter kit with some basic features like authentication, registration, user profile with a sample task module which is built on latest version of bootstrap.This script can be handy enough for your new Laravel+Vue.js project & will surely speed-up your project development time. If you are working first time on Laravel+Vue.js or learning Vue.js then this is perfect script to get started.

Instead of developing your project from scratch, you can choose to start with our script & use the basic features with few clicks. You will also get a responsive bootstrap 4.1 theme by (Wrappixel.com) to give awesome experience to you/your clients.

This script will be updated regularily with latest version of framework & plugins. Please share your feedback, feature request which will be surely implemented in upcoming versions.

THE CODE IS WELL COMMENTED, FOLLOWS PSR-2 CODING STANDARD AND USES LARAVEL REPOSITORY PATTERN. IT IS WRITTEN WITH LOVE BY WWW.SCRIPTMINT.COM.

Here is the example:

Laravel 6.0 Vue.js SPA Bootstrap Admin Starter Kit - 1
Laravel 6.0 Vue.js SPA Bootstrap Admin Starter Kit - 2

What are the pre-requisites to install this script?

Here are list of pre-requisites which is required to install this script:

  • PHP 7.1.3
  • OpenSSL PHP Extension
  • PDO PHP Extension
  • Mbstring PHP Extension
  • Tokenizer PHP Extension
  • XML PHP Extension

The script supports REST Api with example documentation, Here is screenshot of API documentation:

Laravel 6.0 Vue.js SPA Bootstrap Admin Starter Kit - 3

What does it include?

Here are list which is included in this script:

  • Built with Laravel 6.0
  • Vue.js 2.6.10
  • Responsive Bootstrap 4.3.1
  • REST Api
  • Speed-up development with Laravel Mix-Webpack
  • Browser Sync
  • Support Sass
  • JSON based authentication, Uses tymon/jwt-auth
  • Single Page Application (SPA), Uses Vue Router
  • Vuex for data flow
  • Pagination
  • Datepicker
  • Content Security Policy
  • Laravel Telescope

What modules are available with Laravue Starter Kit?

Here are list of pre defined components which is available in this script:

  • Autosize Textarea
  • Date Range Picker
  • File Upload Input
  • File Upload Progress
  • HTML Editor
  • Upload Image

Here are list of modules which is available in this script:

  • User Authentication
  • Social oAuth
  • Reset Password
  • User Registration
  • User Activation
  • Account Approval
  • Two Factor Authentication
  • Screen Lock
  • Login Throttle
  • Reset Password Token Lifetime
  • Login Lifetime
  • Password Strength Meter
  • User List
  • User Profile
  • Change Password
  • User Avatar
  • Sample Todo Module
  • Private Message
  • Database Backup
  • IP Filter
  • Maintenance Mode
  • Multilingual
  • RTL Support
  • Date/Time Format & Timezone
  • Activity Log
  • Email Log
  • Custom Email Templates
  • User Roles & Permissions
  • Multiple Mail Drivers
  • Nexmo SMS Api

FAQ’s

Does this script include all source code with unminified version?

Yes, this includes everything, including composer.json, package.json, webpack.mix.js, different plugins and all in it.

Where can I access documentation?

All the documentation is available at http://support.scriptmint.com which you can access online. In case you face any issue, please raise a ticket at http://support.scriptmint.com. Estimated response time is 48 working hours.

Does author provides installation support?

No, author doesn’t provide installation support in any environment (live or local). You can read the support documentation which is available online.

Will I get support for further development if I have any queries?

Yes, you will get answer of all your queries and issues (if any). Please note that author is not going to teach you coding skill but author is providing a starter kit which you can use to learn, develope Laravel + Vue.js project. It is recommened to have basic knowledge of any PHP framework along with Javascript. Also note, that support is only available to the customers, who have purchased the script from www.codecanyon.net. You need to provide your Envato Username & Purchase code in order to get author support.

Does author provides customization?

Yes, author is available for customization but with extra charge of $15 per hour.

Can I use this script for multiple instance?

No, if you have purchased regular license then you can only use this script only for 1 instance. If anytime, it is found that you have used multiple instance of this script, your support will be blocked immediately.

Don’t hesitate to email us at [email protected]