Archie  Clayton

Archie Clayton

1588488960

How to use the JavaScript Equivalent of Sleep, Wait, Delay, and Pause

JavaScript is the language of web. JS hasn’t been the same since ES5 was released. More and more ideas and features are being ported from different languages and being integrated in JavaScript. One such feature is Promises, which is probably the most widely used thing in JavaScript after ES5 was released.

But one of the things which JavaScript miss is the way to “pause” execution for a while and resume it later. In this post, I’ll discuss how you can achieve that and what it really means to “pause” or “sleep” in JavaScript. Spoiler: JavaScript never really “pauses”

TL;DR

Here’s the copy-pasta code which would do the job:

/**
 * 
 * @param duration Enter duration in seconds
 */
function sleep(duration) {
	return new Promise(resolve => {
		setTimeout(() => {
			resolve()
		}, duration * 1000)
	})
}

But what is really happening here?

setTimeout and the fake Promises

Let’s see a quick example using the above snippet (we’ll discuss what’s happening in it later)

async function performBatchActions() {
	// perform an API call
	await performAPIRequest()

	// sleep for 5 seconds
	await sleep(5)

	// perform an API call again
	await performAPIRequest()
}

This function performBatchActions, when called, would simply execute the performAPIRequest function, wait about 5 seconds, and then call the same function again. Note how I wrote about 5 seconds, and not 5 seconds.

A strong note to put out here, the above code does not guarantee a perfect sleep. It means that if you specify duration to be, say 1 second, JavaScript does not guarantee that it would start running the code after the sleep exactly after 1 second. Why? You may ask. Unfortunately, that’s because timers work in JavaScript, and in general, event loop. However, JavaScript absolutely guarantees that the piece of code after the sleep would never execute before the said time, so we don’t really have a full indeterminate situation, just a partial one, and in most cases, within a margin of a few milliseconds only.

JavaScript is single threaded

A single thread means JavaScript process cannot really go out of the way at all. It has to do all the things - from event listeners, to HTTP callbacks, on the same main thread. And when one thing is executing, another one cannot execute. Consider a webpage in which you have multiple buttons and you run the code above to simulate a sleep for lets say 10 seconds. What do you expect would happen?

Nothing at all. Your webpage would work just fine, your buttons would be responsive, and once the 10 second sleep is done, the code next to it would execute. So it’s evident that JavaScript did not really block the whole main thread because if it did that, your webpage should have frozen and the buttons should have become non-clickable. So how did JavaScript actually pause a single thread, without ever really pausing it?

Meet the Event Loop

Unlike other languages, JavaScript doesn’t just keep on executing code in a linear fashion from top to bottom. It is an asynchronous event driven language with tons of magic in the form of event loop. Event loop splits your code in synchronous and certain events - like timers and HTTP requests. Precisely speaking, there are two queues - task queue and microtask queue. Whenever you run JS, and there’s an asynchronous thing (like a mouseclick event, or a promise) JavaScript throws it in the task queue (or microtask queue) and keeps executing. When it completes a “single tick” - it checks if task queues and microtask queue has some work for it. If yes, then it’ll execute the callback/perform an action.

I would really recommend anyone interested in deep working of event loop to watch this video:

Conclusion

You came here for a simple sleep instruction in JavaScript, ended up learning about one of the core things in JavaScript - event loop! Amazing, isn’t it?

Originally published by Mehul Mohan at https://www.freecodecamp.org

#javascript #web-development

What is GEEK

Buddha Community

How to use the JavaScript Equivalent of Sleep, Wait, Delay, and Pause
CSS Boss

CSS Boss

1606912089

How to create a calculator using javascript - Pure JS tutorials |Web Tutorials

In this video I will tell you How to create a calculator using javascript very easily.

#how to build a simple calculator in javascript #how to create simple calculator using javascript #javascript calculator tutorial #javascript birthday calculator #calculator using javascript and html

Archie  Clayton

Archie Clayton

1588488960

How to use the JavaScript Equivalent of Sleep, Wait, Delay, and Pause

JavaScript is the language of web. JS hasn’t been the same since ES5 was released. More and more ideas and features are being ported from different languages and being integrated in JavaScript. One such feature is Promises, which is probably the most widely used thing in JavaScript after ES5 was released.

But one of the things which JavaScript miss is the way to “pause” execution for a while and resume it later. In this post, I’ll discuss how you can achieve that and what it really means to “pause” or “sleep” in JavaScript. Spoiler: JavaScript never really “pauses”

TL;DR

Here’s the copy-pasta code which would do the job:

/**
 * 
 * @param duration Enter duration in seconds
 */
function sleep(duration) {
	return new Promise(resolve => {
		setTimeout(() => {
			resolve()
		}, duration * 1000)
	})
}

But what is really happening here?

setTimeout and the fake Promises

Let’s see a quick example using the above snippet (we’ll discuss what’s happening in it later)

async function performBatchActions() {
	// perform an API call
	await performAPIRequest()

	// sleep for 5 seconds
	await sleep(5)

	// perform an API call again
	await performAPIRequest()
}

This function performBatchActions, when called, would simply execute the performAPIRequest function, wait about 5 seconds, and then call the same function again. Note how I wrote about 5 seconds, and not 5 seconds.

A strong note to put out here, the above code does not guarantee a perfect sleep. It means that if you specify duration to be, say 1 second, JavaScript does not guarantee that it would start running the code after the sleep exactly after 1 second. Why? You may ask. Unfortunately, that’s because timers work in JavaScript, and in general, event loop. However, JavaScript absolutely guarantees that the piece of code after the sleep would never execute before the said time, so we don’t really have a full indeterminate situation, just a partial one, and in most cases, within a margin of a few milliseconds only.

JavaScript is single threaded

A single thread means JavaScript process cannot really go out of the way at all. It has to do all the things - from event listeners, to HTTP callbacks, on the same main thread. And when one thing is executing, another one cannot execute. Consider a webpage in which you have multiple buttons and you run the code above to simulate a sleep for lets say 10 seconds. What do you expect would happen?

Nothing at all. Your webpage would work just fine, your buttons would be responsive, and once the 10 second sleep is done, the code next to it would execute. So it’s evident that JavaScript did not really block the whole main thread because if it did that, your webpage should have frozen and the buttons should have become non-clickable. So how did JavaScript actually pause a single thread, without ever really pausing it?

Meet the Event Loop

Unlike other languages, JavaScript doesn’t just keep on executing code in a linear fashion from top to bottom. It is an asynchronous event driven language with tons of magic in the form of event loop. Event loop splits your code in synchronous and certain events - like timers and HTTP requests. Precisely speaking, there are two queues - task queue and microtask queue. Whenever you run JS, and there’s an asynchronous thing (like a mouseclick event, or a promise) JavaScript throws it in the task queue (or microtask queue) and keeps executing. When it completes a “single tick” - it checks if task queues and microtask queue has some work for it. If yes, then it’ll execute the callback/perform an action.

I would really recommend anyone interested in deep working of event loop to watch this video:

Conclusion

You came here for a simple sleep instruction in JavaScript, ended up learning about one of the core things in JavaScript - event loop! Amazing, isn’t it?

Originally published by Mehul Mohan at https://www.freecodecamp.org

#javascript #web-development

Rahul Jangid

1622207074

What is JavaScript - Stackfindover - Blog

Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.

Who invented JavaScript?

JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.

What is JavaScript?

JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.

Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.

JavaScript Hello World Program

In JavaScript, ‘document.write‘ is used to represent a string on a browser.

<script type="text/javascript">
	document.write("Hello World!");
</script>

How to comment JavaScript code?

  • For single line comment in JavaScript we have to use // (double slashes)
  • For multiple line comments we have to use / * – – * /
<script type="text/javascript">

//single line comment

/* document.write("Hello"); */

</script>

Advantages and Disadvantages of JavaScript

#javascript #javascript code #javascript hello world #what is javascript #who invented javascript

Hire Dedicated JavaScript Developers -Hire JavaScript Developers

It is said that a digital resource a business has must be interactive in nature, so the website or the business app should be interactive. How do you make the app interactive? With the use of JavaScript.

Does your business need an interactive website or app?

Hire Dedicated JavaScript Developer from WebClues Infotech as the developer we offer is highly skilled and expert in what they do. Our developers are collaborative in nature and work with complete transparency with the customers.

The technology used to develop the overall app by the developers from WebClues Infotech is at par with the latest available technology.

Get your business app with JavaScript

For more inquiry click here https://bit.ly/31eZyDZ

Book Free Interview: https://bit.ly/3dDShFg

#hire dedicated javascript developers #hire javascript developers #top javascript developers for hire #hire javascript developer #hire a freelancer for javascript developer #hire the best javascript developers

Why Use WordPress? What Can You Do With WordPress?

Can you use WordPress for anything other than blogging? To your surprise, yes. WordPress is more than just a blogging tool, and it has helped thousands of websites and web applications to thrive. The use of WordPress powers around 40% of online projects, and today in our blog, we would visit some amazing uses of WordPress other than blogging.
What Is The Use Of WordPress?

WordPress is the most popular website platform in the world. It is the first choice of businesses that want to set a feature-rich and dynamic Content Management System. So, if you ask what WordPress is used for, the answer is – everything. It is a super-flexible, feature-rich and secure platform that offers everything to build unique websites and applications. Let’s start knowing them:

1. Multiple Websites Under A Single Installation
WordPress Multisite allows you to develop multiple sites from a single WordPress installation. You can download WordPress and start building websites you want to launch under a single server. Literally speaking, you can handle hundreds of sites from one single dashboard, which now needs applause.
It is a highly efficient platform that allows you to easily run several websites under the same login credentials. One of the best things about WordPress is the themes it has to offer. You can simply download them and plugin for various sites and save space on sites without losing their speed.

2. WordPress Social Network
WordPress can be used for high-end projects such as Social Media Network. If you don’t have the money and patience to hire a coder and invest months in building a feature-rich social media site, go for WordPress. It is one of the most amazing uses of WordPress. Its stunning CMS is unbeatable. And you can build sites as good as Facebook or Reddit etc. It can just make the process a lot easier.
To set up a social media network, you would have to download a WordPress Plugin called BuddyPress. It would allow you to connect a community page with ease and would provide all the necessary features of a community or social media. It has direct messaging, activity stream, user groups, extended profiles, and so much more. You just have to download and configure it.
If BuddyPress doesn’t meet all your needs, don’t give up on your dreams. You can try out WP Symposium or PeepSo. There are also several themes you can use to build a social network.

3. Create A Forum For Your Brand’s Community
Communities are very important for your business. They help you stay in constant connection with your users and consumers. And allow you to turn them into a loyal customer base. Meanwhile, there are many good technologies that can be used for building a community page – the good old WordPress is still the best.
It is the best community development technology. If you want to build your online community, you need to consider all the amazing features you get with WordPress. Plugins such as BB Press is an open-source, template-driven PHP/ MySQL forum software. It is very simple and doesn’t hamper the experience of the website.
Other tools such as wpFoRo and Asgaros Forum are equally good for creating a community blog. They are lightweight tools that are easy to manage and integrate with your WordPress site easily. However, there is only one tiny problem; you need to have some technical knowledge to build a WordPress Community blog page.

4. Shortcodes
Since we gave you a problem in the previous section, we would also give you a perfect solution for it. You might not know to code, but you have shortcodes. Shortcodes help you execute functions without having to code. It is an easy way to build an amazing website, add new features, customize plugins easily. They are short lines of code, and rather than memorizing multiple lines; you can have zero technical knowledge and start building a feature-rich website or application.
There are also plugins like Shortcoder, Shortcodes Ultimate, and the Basics available on WordPress that can be used, and you would not even have to remember the shortcodes.

5. Build Online Stores
If you still think about why to use WordPress, use it to build an online store. You can start selling your goods online and start selling. It is an affordable technology that helps you build a feature-rich eCommerce store with WordPress.
WooCommerce is an extension of WordPress and is one of the most used eCommerce solutions. WooCommerce holds a 28% share of the global market and is one of the best ways to set up an online store. It allows you to build user-friendly and professional online stores and has thousands of free and paid extensions. Moreover as an open-source platform, and you don’t have to pay for the license.
Apart from WooCommerce, there are Easy Digital Downloads, iThemes Exchange, Shopify eCommerce plugin, and so much more available.

6. Security Features
WordPress takes security very seriously. It offers tons of external solutions that help you in safeguarding your WordPress site. While there is no way to ensure 100% security, it provides regular updates with security patches and provides several plugins to help with backups, two-factor authorization, and more.
By choosing hosting providers like WP Engine, you can improve the security of the website. It helps in threat detection, manage patching and updates, and internal security audits for the customers, and so much more.

Read More

#use of wordpress #use wordpress for business website #use wordpress for website #what is use of wordpress #why use wordpress #why use wordpress to build a website