Thursday, November 28, 2019

Delay, Sleep, Pause, & Wait in JavaScript

Timing Issues in JavaScript: Implementing a Sleep Function

Many programming languages have a sleep function that will delay a program's execution for a given number of seconds. This functionality is absent from JavaScript, however, owing to its asynchronous nature. In this article, we'll look briefly at why this might be, then how we can implement a sleep function ourselves.

Understanding JavaScript's Execution Model

Before we get going, it's important to make sure we understand JavaScript's execution model correctly.

Consider the following Ruby code:

require 'net/http'
require 'json'

url = 'https://api.github.com/users/jameshibbard'
uri = URI(url)
response = JSON.parse(Net::HTTP.get(uri))
puts response['public_repos']
puts "Hello!"

As one might expect, this code makes a request to the GitHub API to fetch my user data. It then parses the response, outputs the number of public repos attributed to my GitHub account and finally prints "Hello!" to the screen. Execution goes from top to bottom.

Contrast that with the equivalent JavaScript version:

fetch('https://api.github.com/users/jameshibbard')
  .then(res => res.json())
  .then(json => console.log(json.public_repos));
console.log("Hello!");

If you run this code, it will output "Hello!" to the screen, then the number of public repos attributed to my GitHub account.

This is because fetching data from an API is an asynchronous operation in JavaScript. The JavaScript interpreter will encounter the fetch command and dispatch the request. It will not, however, wait for the request to complete. Rather, it will continue on its way, output "Hello!" to the console, then when the request returns a couple of hundred milliseconds later, it will output the number of repos.

If any of this is news to you, you should watch this excellent conference talk: What the heck is the event loop anyway?.

You Might Not Actually Need a Sleep Function

Now that we have a better understanding of JavaScript's execution model, let's have a look at how JavaScript handles delays and asynchronous operations.

Create a Simple Delay Using setTimeout

The standard way of creating a delay in JavaScript is to use its setTimeout method. For example:

console.log("Hello");
setTimeout(() => {  console.log("World!"); }, 2000);

This would log "Hello" to the console, then after two seconds "World!" And in many cases, this is enough: do something, wait, then do something else. Sorted!

However, please be aware that setTimeout is an asynchronous method. Try altering the previous code like so:

console.log("Hello");
setTimeout(() => { console.log("World!"); }, 2000);
console.log("Goodbye!");

It will log:

Hello
Goodbye!
World!

Waiting for Things with setTimeout

It's also possible to use setTimeout (or its cousin setInterval) to keep JavaScript waiting until a condition is met. For example, here's how you might use setTimeout to wait for a certain element to appear on a web page:

function pollDOM () {
  const el = document.querySelector('my-element');

  if (el.length) {
    // Do something with el
  } else {
    setTimeout(pollDOM, 300); // try again in 300 milliseconds
  }
}

pollDOM();

This assumes the element will turn up at some point. If you're not sure that's the case, you'll need to look at canceling the timer (using clearTimeout or clearInterval).

If you'd like to find out more about JavaScript's setTimeout method, please consult our tutorial which has plenty of examples to get you going.

The post Delay, Sleep, Pause, & Wait in JavaScript appeared first on SitePoint.


by James Hibbard via SitePoint

LinkedIn Transparency Report Reveals Data on User Privacy, Spam Accounts and More

Most tech companies and social media platforms have started to release transparency reports, with the initial purpose of these reports is to try and give users a sense of understanding regarding what the platform or company is doing in order to protect their privacy and ensure that they would not...

[ This is a content summary only. Visit our website https://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Zia Muhammad via Digital Information World

Wednesday, November 27, 2019

WhatsApp for iPhone Receives a Major Update Packed with Several New Features!

iPhone users will now be getting their hands on an updated version of WhatsApp (2.19.120). What’s exciting about the update is that it comes with a number of cool features. A few weeks ago, the messaging service introduced the much-needed group privacy settings for both Android and iPhone. However,...

[ This is a content summary only. Visit our website https://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Ali Siddiqui via Digital Information World

Facebook’s Android App Might be Getting a Dark Mode Soon

A lot of social media platforms and instant messaging services have started offering dark modes. A big part of the reason why this is the case has to do with the numerous health concerns that arose from people that used smartphones or stared at their screens all day, with the impact that this was...

[ This is a content summary only. Visit our website https://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Zia Muhammad via Digital Information World

Button Style 95

The post Button Style 95 appeared first on Best jQuery.


by Admin via Best jQuery

Bootstrap Vertical Tab 53

The post Bootstrap Vertical Tab 53 appeared first on Best jQuery.


by Admin via Best jQuery

Study Shows How to Improve Your Social Media Posts: 9 Hints for Better Results in 2020

Brands, influencers and people post their ideas on social media, putting in their best effort to appeal to the public and to gain more recognition and ultimately to sell more. So here’s the question that arises: Is crafting the perfect post a utopian task? There are more KPIs than ever before...

[ This is a content summary only. Visit our website https://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Web Desk via Digital Information World