Categories
JavaScript Answers

How to Use setTimeout Sequentially in JavaScript?

Sometimes, we want to use setTimeout sequentially in JavaScript.

In this article, we’ll look at how to use setTimeout sequentially in JavaScript.

Use setTimeout Sequentially in JavaScript

To use setTimeout sequentially in JavaScript, we can create a promise with a callback that calls setTimeout and use it multiple times.

For instance, we can write:

const sleep = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms));
}

(async () => {
  await sleep(100)
  await sleep(200)
})()

We create the sleep function that returns a promise we create with the Promise constructor.

The callback use resolve as the callback for setTimeout .

ms is the number of milliseconds to delay the call of resolve .

Then we create an async function that calls sleep with 100 and 200 milliseconds and call it immediately.

Conclusion

To use setTimeout sequentially in JavaScript, we can create a promise with a callback that calls setTimeout and use it multiple times.

Categories
JavaScript Answers

How to Get the Entered Value From a TinyMCE Text Area?

Sometimes, we want to get the entered value from a TinyMCE text area.

In this article, we’ll look at how to get the entered value from a TinyMCE text area.

Get the Entered Value From a TinyMCE Text Area

To get the entered value from a TinyMCE text area, we can use the tinyMCE.activeEditor.getContent() method.

For instance, if we have the following HTML:

<script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>

<form method="post">
  <textarea id="mytextarea">Hello, World!</textarea>
</form>

to add the TinyMCE script and text area, then we can get the value when the editor is initialized by writing:

tinymce.init({
  selector: '#mytextarea',
  setup(editor) {
    editor.on('init', () => {
      console.log(tinyMCE.activeEditor.getContent())
    })
  }
});

We call tinymce.init to create the text editor.

selector is the textarea element that we want to convert to a TinyMCE editor.

Then we have the setup method that calls editor.on with 'init' to watch when the editor is initialized.

Then callback will run when it’s initialized, so we can get the input value of the editor when the editor is initialized with tinyMCE.activeEditor.getContent() .

Therefore, we should see '<p>Hello, World!</p>’ logged.

Conclusion

To get the entered value from a TinyMCE text area, we can use the tinyMCE.activeEditor.getContent() method.

Categories
JavaScript Answers

How to Print All Methods in a JavaScript Object?

Sometimes, we want to print all methods in a JavaScript object.

In this article, we’ll look at how to print all methods in a JavaScript object.

Print All Methods in a JavaScript Object

To print all methods in a JavaScript object, we can use the Object.keys method to get all the top-level property keys of the JavaScript object in an array.

Then we call the filter method to filter out the keys for values that aren’t methods with the typeof operator.

Then we map the method keys to methods with map .

For instance, we can write:

const getMethods = (obj) => {
  return Object.keys(obj)
    .filter((key) => typeof obj[key] === 'function')
    .map((key) => obj[key]);
}

const obj = {
  foo() {},
  bar: 1
}
console.log(getMethods(obj))

We have the getMethods function that takes an obj object.

Then we call Object.keys with obj to get the top-level string property keys.

Then we call filter with a function that returns the properties that are functions with the typeof operator.

Next, we call map to map each key to their corresponding value.

Therefore, if we call getMethods with obj , we get the foo method in the array.

Conclusion

To print all methods in a JavaScript object, we can use the Object.keys method to get all the top-level property keys of the JavaScript object in an array.

Categories
JavaScript Answers

How to Use the Mutation Observer for Watching the Creation of New Elements?

Sometimes, we want to use the mutation observer for watching the creation of new elements.

In this article, we’ll look at how to use the mutation observer for watching the creation of new elements.

Use the Mutation Observer for Watching the Creation of New Elements

To use the mutation observer for watching the creation of new elements, we can use the MutationObserver constructor to watch the element that contains the element that will be added.

For instance, if we have the following HTML:

<div id='foo'>
  click me
</div>

and we want to watch for an element with ID bar to be added, then we can write:

const foo = document.querySelector('#foo')
foo.addEventListener('click', () => {
  const bar = document.createElement('div')
  bar.id = 'bar'
  foo.appendChild(bar)
})

const obs = new MutationObserver((mutations, observer) => {
  for (const m of mutations) {
    for (const n of m.addedNodes) {
      if (n.id === "bar") {
        console.log("bar was added!");
      }
    }
  }
});

obs.observe(foo, {
  childList: true
});

We select the div with document.querySelector .

Then we call foo.addEventListener to add a click listener to the foo element.

In the click listener callback, we call document.createElement to create a div and append it into the div with ID foo with appendChild .

bar.id is set to 'bar' so the new div’s ID is bar .

Next, we create a new MutationObserver instance with a callback that loops through all the mutations and in it, we loop through all the nodes that are added, which are stored in m.addedNodes .

Inside the inner loop, we check for an element that’s added with ID bar .

If it’s true , then we log 'bar was added!' .

Therefore, when we click on the foo div, we’ll see the message logged.

Conclusion

To use the mutation observer for watching the creation of new elements, we can use the MutationObserver constructor to watch the element that contains the element that will be added.

Categories
Day.js

Manipulating Dates with Day.js — Calendar Time and Date-Time Difference

Day.js is a JavaScript library that lets us manipulate dates in our apps.

In this article, we’ll look at how to use Day.js to manipulate dates in our JavaScript apps.

Calendar Time

We can get a date in calendar time format with the calendar method that comes with the calendar plugin.

For instance, we can write:

const dayjs = require("dayjs");
const calendar = require("dayjs/plugin/calendar");
dayjs.extend(calendar);

const result = dayjs().calendar();
console.log(result);

We call calendar to get the time of today.

Therefore, if the time is 1:23 pm now, we get ‘Today at 1:23 PM‘ for result .

Date-Time Difference

We can get the date-time difference between 2 date-times with the diff method.

For instance, we can write:

const dayjs = require("dayjs");
const date1 = dayjs("2020-01-25");
const date2 = dayjs("2018-06-05");
const result = date1.diff(date2);
console.log(result);

to get the date difference between January 25, 2020, and June 5, 2018.

Therefore, result is 51757200000 and the number is in milliseconds.

We can get the date-time differences in a different unit.

For instance, we can get the difference in months by writing:

const dayjs = require("dayjs");
const date1 = dayjs("2020-01-25");
const date2 = dayjs("2018-06-05");
const result = date1.diff(date2, 'month');
console.log(result);

We passed in 'month' as the 2nd argument of diff to get the month difference between date1 and date2 .

Conclusion

Day.js is a JavaScript library that lets us manipulate dates in our apps.