Updates from August, 2020 Toggle Comment Threads | Keyboard Shortcuts

  • shashankgee 5:42 am on 10 Aug 2020 Permalink | Reply  

    async / await 

    
    // var promise = new Promise(function(resolve,reject){
    
    //   resolve(1);
    
    // });
    
    // promise.then(function success(data){
    // console.log(data);
    // return data+1;
    // }).then(function(data){
    // console.log('chaining--',data)
    // return data + 1;
    // }).then(function(data){
    //   console.log('chaining--',data)
    // })
    // .catch(function(err){
    // console.error(err);
    // });
    
    //fetch
    let url = 'https://jsonplaceholder.typicode.com/users/3'
    let res = fetch(url);
    
    // res.then(function(res){
    //   return   res.json();
    // }).then(function(data){
    //   console.log("data",data)
    // })
    
    // res.then(res => res.json())
    //    .then(data=>{
    //      console.log("data--",data);
    //    })
    
    
    
    
    
    async function getData(){
    try {
       let url = 'https://jsonplaceholder.typicode.com';
       let result = await fetch(url);
       let resJson =  await result.json();
       let data = await resJson;
    
     console.log('getting the await data',data);
    }
    catch(err){
    console.log('in catch block',err);
    }
    }
    
    getData();
    
     
  • shashankgee 3:16 am on 4 Aug 2020 Permalink | Reply  

    Understanding “same-site” and “same-origin” 

    https://web.dev/same-site-same-origin/

     
  • shashankgee 12:18 am on 14 Jul 2020 Permalink | Reply  

    Debouncing and throttling 

    Debouncing and throttling are two related but different techniques for improving performance of events in JavaScript plugins and applications.

    The terms are often used interchangeably, but they’re not the same thing. Let’s clear that up.

    1. With throttling, you run a function immediately, and wait a specified amount of time before running it again. Any additional attempts to run it before that time period is over are ignored.
    2. With debouncing, you wait a specified amount of time before running a function. The last attempt to run the function is the one that runs, and any previous attempts within the time period are ignored.

    Let’s look at examples of both techniques.

    Logging button clicks

    For both examples, we’ll be counting the number of clicks on a button.

    <button id="click-me">Click Me</button>
    

    We’re going to detect when the user clicks the button, and will log it to the console.

    var count = 0;
    
    document.addEventListener('click', function (event) {
    
    	// Only run if the #click-me button was clicked
    	if (event.target.id !== 'click-me') return;
    
    	// Update the count by 1
    	count++;
    
    	// Log the count to the console
    	console.log('true count', count);
    
    });
    
    

    Here’s a demo.

    But what if, for performance reasons, you wanted to limit how frequently the log actually happened to once every 3 seconds?

    Let’s look at how to do that using throttling and debouncing techniques.

    Throttling

    With throttling, we’ll setup a variable, wait, to tell us if we should wait before running the function again or not.

    For learning purposes, I also want to show the difference between actual clicks and how many times the throttled function runs. We’ll setup a second variable to track the throttled count, so that we can compare it to the actual number of times the button was clicked.

    var count = 0;
    var throttleCount = 0;
    var wait = false;
    
    

    When the event listener runs, we’ll still update count by one.

    Then, we’ll update the throttleCount by one as well, and log both counts into the console.

    var count = 0;
    var throttleCount = 0;
    var wait = false;
    
    document.addEventListener('click', function (event) {
    
    	// Only run if the #click-me button was clicked
    	if (event.target.id !== 'click-me') return;
    
    	// Update the count by 1
    	count++;
    
    	// Update the throttleCount
    	throttleCount++;
    
    	// Log the counts
    	console.log('true count', count);
    	console.log('throttled count', throttleCount);
    
    });
    
    

    Now we’re ready to actually throttle the function.

    After logging the counts to the console, we’ll set wait to true. We’ll use the setTimeout() method to set it back to false after 3 seconds (3000 milliseconds)

    var count = 0;
    var throttleCount = 0;
    var wait = false;
    
    document.addEventListener('click', function (event) {
    
    	// Only run if the #click-me button was clicked
    	if (event.target.id !== 'click-me') return;
    
    	// Update the count by 1
    	count++;
    
    	// Update the throttleCount
    	throttleCount++;
    
    	// Log the counts
    	console.log('true count', count);
    	console.log('throttled count', throttleCount);
    
    	// Ignore any future requests for the next 3 seconds
    	wait = true;
    	setTimeout(function (event) {
    		wait = false;
    	}, 3000);
    
    });
    
    

    Before updating throttleCount and logging anything, we’ll check if wait is true. If it is, we’ll return to end the function and do nothing.

    var count = 0;
    var throttleCount = 0;
    var wait = false;
    
    document.addEventListener('click', function (event) {
    
    	// Only run if the #click-me button was clicked
    	if (event.target.id !== 'click-me') return;
    
    	// Update the count by 1
    	count++;
    
    	// If currently throttled, ignore the request
    	if (wait) return;
    
    	// Update the throttleCount
    	throttleCount++;
    
    	// Log the counts
    	console.log('true count', count);
    	console.log('throttled count', throttleCount);
    
    	// Ignore any future requests for the next 3 seconds
    	wait = true;
    	setTimeout(function (event) {
    		wait = false;
    	}, 3000);
    
    });
    
    

    Now, the function will only run once every three seconds.

    Here’s a demo of throttling. Click the button a bunch of times to see it in action.

    Debouncing

    Debouncing is actually simpler to implement.

    We’ll again create a special variable, debounceCount, to track the number of debounced clicks versus actual clicks.

    var count = 0;
    var debounceCount = 0;
    
    

    With debouncing, we delay running our function until a certain period of time has passed using the setTimeout() method.

    var count = 0;
    var debounceCount = 0;
    
    document.addEventListener('click', function (event) {
    
    	// Only run if the #click-me button was clicked
    	if (event.target.id !== 'click-me') return;
    
    	// Update the count by 1
    	count++;
    
    	// Update and log the counts after 3 seconds
    	setTimeout(function () {
    
    		// Update the debounceCount
    		debounceCount++;
    
    		// Log the counts to the console
    		console.log('true count', count);
    		console.log('debounced count', debounceCount);
    
    	}, 3000);
    
    });
    
    

    However, if the button is clicked again, we want to ignore the currently pending function and replace it with the new one.

    To do that, we’ll assign our setTimeout() to a variable. When the event handler runs, we’ll clear any existing timeout before setting a new one.

    var count = 0;
    var debounceCount = 0;
    var debounce;
    
    document.addEventListener('click', function (event) {
    
    	// Only run if the #click-me button was clicked
    	if (event.target.id !== 'click-me') return;
    
    	// Update the count by 1
    	count++;
    
    	// Clear any existing debounce event
    	clearTimeout(debounce);
    
    	// Update and log the counts after 3 seconds
    	debounce = setTimeout(function () {
    
    		// Update the debounceCount
    		debounceCount++;
    
    		// Log the counts to the console
    		console.log('true count', count);
    		console.log('debounced count', debounceCount);
    
    	}, 3000);
    
    });
    
    

    Here’s a demo of debouncing.

    As you can see, with debouncing, nothing is logged into the console until three seconds after the last click. If you click the button continuously for six seconds, nothing is logged until three seconds after that, nine seconds from when you started.

    Which approach should you use?

    Which approach you choose will depend on what you’re trying to do, and what the desired user experience is.

    For example, you might use debouncing if you’re sending some updates to a database in reaction to user interactions, since the timing of those updates has little impact on the UI. You might debounce scroll events to run when the user is completely done scrolling.

    For interactions that update the UI, throttling might make more sense, because they’ll run at predictable intervals.

     
  • shashankgee 3:48 am on 1 Jul 2020 Permalink | Reply  

    come up with the dnm code 

    to check the variable type : it gives absolute results:

    Object.prototype.toString.call(null).slice(8,-1);
    "Null"
    Object.prototype.toString.call(null).slice(8,-1);
    "Null"
    Object.prototype.toString.call(undefined).slice(8,-1);
    "Undefined"
    Object.prototype.toString.call(false).slice(8,-1);
    "Boolean"
    Object.prototype.toString.call({}).slice(8,-1);
    "Object"
     
  • shashankgee 3:22 am on 30 Jun 2020 Permalink | Reply  

    Promises 

    let promise = new Promise((resolve,reject) => {
         resolve(`Promise is Resolved !`);
    });
    
    promise.then(function success(successObj){
      alert(successObj);
    }, function error(errorObj){
    alert(errorObj);
    })
    
    //if promise reject or throws some errors catch block will be called.
    let promise1 = new Promise((resolve,reject) => {
        throw new Error(`Promise is failed !`)
    });
    
    promise1.then(function success(obj){
    
    },function error(eObj){
    
    }).catch( error => {
        alert(`Cathing exception ${error}`);
    })
     
  • shashankgee 1:39 am on 19 Feb 2020 Permalink | Reply  

    Best trick to get all properties of any Javascript object 

    console.dir

    The dir() method displays an interactive list of the properties and methods of the specified JavaScript object.

    Get properties and methods of the Array object:

    console.dir(Array);

    https://levelup.gitconnected.com/best-trick-to-get-all-properties-of-any-javascript-object-2c68217a138a

     
  • shashankgee 1:14 am on 19 Feb 2020 Permalink | Reply  

    are let and const variables not hoisted? 

    The answer is a bit more complicated than that. All declarations (function, var, let, const and class) are hoisted in JavaScript, while the var declarations are initialized with undefined, but let and const declarations remain uninitialized.

    https://blog.bitsrc.io/hoisting-in-modern-javascript-let-const-and-var-b290405adfda

    Hoisting with let

    Variables declared with let are still hoisted, but they don’t automatically receive a value of undefined the way variables declared with var do.

    The browser knows they exist, but has no value at all for them. Trying to log a variable declared with let before it’s actually declared throws an error.

    // While the name was hoisted, it has no defined value and throws an error
    // Uncaught ReferenceError: l is not defined
    console.log(l);
    
    // The value gets defined
    let l = 'declare with let';
    
    // logs "declare with var"
    console.log(l);
    
    

    This gap between when a variable declared with let is hoisted and when it actually gets declared is known as the temporal dead zone.

    Steve Griffith has a great video on this if you want to learn more.

     
  • shashankgee 12:45 am on 19 Feb 2020 Permalink | Reply
    Tags: Json.Parse, Json.stringify   

    5 places we can use JSON.stringify() and JSON.parse() 

    https://levelup.gitconnected.com/5-uses-of-json-stringify-json-parse-9b79cb4d9645

    1. Storing and retrieving data from localStorage or sessionStorage

    localStorage and sessionStorage properties allow us to save key/value pairs in a web browser.

    Local storage can only save strings, so storing objects requires that they be converted into strings using JSON.stringify before storing them. You can’t ask local storage to store an object directly because it will store “[object Object]”.

    Also, we need to run JSON.parse when retrieving the data from local storage. Let’s see the example below:

    • XMLHttpRequest to fetch the data from a server

      hen retrieving the response from an API, by default the response comes in the string format, and we need to parse it into JSON
    • Stringify the body when making a POST request

      We need to stringify the body object when sending a POST request to the server. Let’s see the example below.
    • Deep cloning a JavaScript object

    Copying objects in JavaScript can be tricky. There are different ways to perform a shallow copy, which is the default behaviour in most of the cases. However, it can be much more challenging to create a deep copy of an object.

    By using JSON.stringify, we can create a deep clone of an object in JavaScript.

    Convert any data type into a string We can convert any kind of data type value into a string by using JSON.stringify.
     
  • shashankgee 12:26 am on 11 Feb 2020 Permalink | Reply
    Tags: , quiz, this   

    HOW ‘this’ works in javascript 

    https://dev.to/liaowow/take-this-quiz-understand-how-this-works-in-javascript-44dj

     
  • shashankgee 12:53 am on 10 Jan 2020 Permalink | Reply
    Tags: convert html, , pdf, to   

    How to generate PDF with JavaScript 

    please refer the below blog.

    https://levelup.gitconnected.com/how-to-generate-pdf-invoices-with-javascript-159279f9243e

     
c
Compose new post
j
Next post/Next comment
k
Previous post/Previous comment
r
Reply
e
Edit
o
Show/Hide comments
t
Go to top
l
Go to login
h
Show/Hide help
shift + esc
Cancel