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 Resize Then Crop an Image with HTML Canvas and JavaScript?

Sometimes, we want to resize then crop an image with HTML canvas and JavaScript.

In this article, we’ll look at how to resize then crop an image with HTML canvas and JavaScript.

Resize Then Crop an Image with HTML Canvas and JavaScript

To resize then crop an image with HTML canvas and JavaScript, we can call the drawImage method with the original image with the coordinates of the boundaries of the image we want to crop.

For instance, if we have the following HTML:

Image: <br/>
<img src="https://i.stack.imgur.com/I4jXc.png" /><br/>
Canvas: <br/>
<canvas id="canvas" width="300" height="300"></canvas>

we write:

const image = new Image()
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d');

image.src = 'https://i.stack.imgur.com/I4jXc.png';

image.onload = () => {
  ctx.drawImage(image,
    70, 20,
    50, 50,
    0, 0,
    100, 100);
}

to do the cropping.

We create an image element with the Image constructor.

Then we get the canvas with document.getElementById .

Next, we get the canvas context with getContext .

Then we setr the src property of thr image to the image URL.

This will trigger the image.onload method to run.

In the onload method, we call drawImage with the

  • image
  • x and y coordinates of the top left corner
  • width of the part of the source image to get relative to the top left corner
  • height of part of source image to get relative to the top left corner
  • x and y coordinates of the top left corner of the cropped image
  • width and height of the cropped image

in this order.

Therefore, we should get the ‘o’ from the word ‘Google’ in the image.

Conclusion

To resize then crop an image with HTML canvas and JavaScript, we can call the drawImage method with the original image with the coordinates of the boundaries of the image we want to crop.

Categories
JavaScript Answers

How to Compute the Intersection of Two Arrays in JavaScript?

Sometimes, we want to compute the intersection of two arrays in JavaScript.

In this article, we’ll look at how to compute the intersection of two arrays in JavaScript.

Compute the Intersection of Two Arrays in JavaScript

To compute the intersection of two arrays in JavaScript, we can use the array filter method with the includes method to get the elements that are in both arrays and return them in an array.

For instance, we can write:

const arr1 = ["mike", "sue", "tom", "kathy", "henry"];
const arr2 = ["howey", "jim", "sue", "jennifer", "kathy", "hank", "alex"];

const result = arr1.filter((n) => {
  return arr2.includes(n);
});
console.log(result)

to get all the name strings that are in both arr1 and arr2 by calling arr1.filter with a callback that returns the condition that the items are also included with arr2 with arr2.includes(n) .

Then we assign the returned result to result .

Therefore, result is [“sue”, “kathy”] .

Conclusion

To compute the intersection of two arrays in JavaScript, we can use the array filter method with the includes method to get the elements that are in both arrays and return them in an array.

Categories
JavaScript Answers

How to Find All the Days in a Month with the JavaScript Date Object?

Sometimes, we want to find all the days in a month with the JavaScript Date object.

In this article, we’ll look at how to find all the days in a month with the JavaScript Date object.

Find All the Days in a Month with the JavaScript Date Object

To find all the days in a month with the JavaScript Date object, we can create an array with the all dates of the month in it.

To do this, we write:

const getDaysInMonth = (month, year) => {
  return new Array(31)
    .fill('')
    .map((v, i) => new Date(year, month - 1, i + 1))
    .filter(v => v.getMonth() === month - 1)
}

console.log(getDaysInMonth(2, 2020))

We create an array with 31 entries initally with new Array(31) .

Then we call fill to fill the empty slots with empty strings.

Next, w call map to map each index, with the dates of the month with new Date(year, month — 1, i + 1) .

JavaScript date months starts with 0 for January to 11 for December, so we’ve to subtract month by 1.

And we’ve to add 1 to 1 to get all the days of the month.

If the day of the month exceeds, the max, the month will be incremented by 1.

So we can just call filter to filter out all the dates with the month that’s 1 more than month — 1 to get the right dates for month .

Therefore, the console log should have 29 days in it since February 2020 has 29 days.

Conclusion

To find all the days in a month with the JavaScript Date object, we can create an array with the all dates of the month in it.

Categories
JavaScript Answers

How to Check if a HTML5 Video is Ready with JavaScript?

Sometimes, we want to check if a HTML5 video is ready with JavaScript.

In this article, we’ll look at how to check if a HTML5 video is ready with JavaScript.

Check if a HTML5 Video is Ready with JavaScript

To check if a HTML5 video is ready with JavaScript, we can listen to the canplay event.

If it’s emitted, then the video is ready.

For instance, if we have:

<video src='https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4'></video>

Then we can listen for the canplay event by writing:

const video = document.querySelector('video')
video.addEventListener('canplay', () => {
  console.log('ready')
})

We select the video element with document.querySelector.

Then we call addEventListener with 'canplay' to listen to the canplay event.

The 2nd argument is the event handler for the canplay event, which runs when the video is ready to be played.

Conclusion

To check if a HTML5 video is ready with JavaScript, we can listen to the canplay event.

If it’s emitted, then the video is ready.