Categories
JavaScript Answers

How to Count Animation from Number A to B with JavaScript?

Sometimes, we want to count animation from number A to B with JavaScript.

In this article, we’ll look at how to count animation from number A to B with JavaScript.

Count Animation from Number A to B with JavaScript

To count animation from number A to B with JavaScript, we can use the requestAnimationFrame method to update the number.

For instance, we can write:

const animateValue = (obj, start, end, duration) => {
  let startTimestamp = null;
  const step = (timestamp) => {
    if (!startTimestamp) startTimestamp = timestamp;
    const progress = Math.min((timestamp - startTimestamp) / duration, 1);
    obj.innerHTML = Math.floor(progress * (end - start) + start);
    if (progress < 1) {
      window.requestAnimationFrame(step);
    }
  };
  window.requestAnimationFrame(step);
}

const obj = document.getElementById('value');
animateValue(obj, 100, -25, 2000);

to create the animateValue function that does the animation.

And we write:

<div id="value">100</div>

to add the number display.

It takes the obj parameter that is set to the element to update.

start and end are the start and end numbers for the animation.

duration is the duration of the animation.

We start the animation by setting the startTimestamp .

Then we define the step funtion that updates the startTimestamp if it’s not defined.

Next, we calculate the progress of the animation by taking the difference between timestamp and startTimestamp , then dividing that by the duration .

Then we update the innerHTML property of obj to update the number displayed.

Then if progress is less than 1, which means the animation isn’t finished, then we call window.requestAnimationFrame with step to update the number display.

Below the step function, we call window.requestAnimationFrame to start the animation.

Finally, we get the div with ID value and call animateValue to run the animation.

Now we should see the number animate from 100 to -25.

Conclusion

To count animation from number A to B with JavaScript, we can use the requestAnimationFrame method to update the number.

Categories
JavaScript Answers

How to Calculate Frames Per Second in the Canvas Using JavaScript’s requestAnimationFrame Function?

Sometimes, we want to calculate frames per second (FPS) in the canvas using JavaScript’s requestAnimationFrame function.

In this article, we’ll look at how to calculate FPS in the canvas using JavaScript’s requestAnimationFrame function.

Calculate FPS in the Canvas Using JavaScript’s requestAnimationFrame Function

To calculate FPS in the canvas using JavaScript’s requestAnimationFrame function, we can create our own function that gets the number of timestamps that are added to an array in one second.

Then the length of that array is the FPS value.

To do this, we write:

let fps = 1;
const times = [];
const fpsLoop = (timestamp) => {
  while (times.length > 0 && times[0] <= timestamp - 1000) {
    times.shift();
  }
  times.push(timestamp);
  fps = times.length;
  console.log(fps);
  requestAnimationFrame(fpsLoop);
}

requestAnimationFrame(fpsLoop);

We create the times array to hold the array of timestamps.

Then the length of times is the FPS value.

Next, we create the fpsLoop to remove the entries in the times array is times[0] is less than or equal to timestamp — 1000 and times.length is bigger than 0 to remove the timestamps that are added before 1 second.

Then we push the timestamp into the times array.

And we assign times.length to fps to get the FPS value.

Next, we call requestAnimation with fpsLoop to run the function indefinitely.

And we call requestAnimation with fpsLoop in the last line to start the measurement.

Conclusion

To calculate FPS in the canvas using JavaScript’s requestAnimationFrame function, we can create our own function that gets the number of timestamps that are added to an array in one second.

Then the length of that array is the FPS value.

Categories
JavaScript Answers

How to Force a Page Scroll Position to the Top at Page Refresh with JavaScript?

Sometimes, we want to force a page scroll position to the top at page refresh with JavaScript.

In this article, we’ll look at how to force a page scroll position to the top at page refresh with JavaScript.

Force a Page Scroll Position to the Top at Page Refresh with JavaScript

To force a page scroll position to the top at page refresh with JavaScript, we can use the window.scrollTo method to scroll the page to the position we want in the beforeunload event handler.

For instance, we can write:

window.onbeforeunload = () => {  
  window.scrollTo(0, 0);  
};

to a function that calls window.scrollTo method with the x and y coordinates of the page to scroll to as the page is being refreshed.

Conclusion

To force a page scroll position to the top at page refresh with JavaScript, we can use the window.scrollTo method to scroll the page to the position we want in the beforeunload event handler.

Categories
JavaScript Answers

How to Convert a JavaScript String into an Array of Integers?

Sometimes, we want to convert a JavaScript string into an array of integers.

In this article, we’ll look at how to convert a JavaScript string into an array of integers.

Convert a JavaScript String into an Array of Integers

To convert a JavaScript string into an array of integers, we can use the JavaScript string’s split method with the array filter method to keep only the numbers.

Then we call map with Number to convert all the values into numbers.

For instance, we can write:

const str = "5 6 7 69 foo"
const intArray = str.split(" ").map(Number).filter(Boolean);
console.log(intArray)

We have the str string which we want to extract the numbers from and put them into the array.

To do that, we call split with a space string to split the string by its spaces and put the split strings into an array.

Then we call map with Number to convert all the values into numbers.

Then we call filter to filter the items that aren’t numbers.

NaN is falsy so any value that can’t be converted to numbers is filtered out.

Therefore, intArray is:

[5, 6, 7, 69]

Conclusion

To convert a JavaScript string into an array of integers, we can use the JavaScript string’s split method with the array filter method to keep only the numbers.

Then we call map with Number to convert all the values into numbers.

Categories
JavaScript Answers

How to Use JavaScript Speech Synthesis with Longer Texts?

Sometimes, we want to use JavaScript speech synthesis with longer texts.

In this article, we’ll look at how to use JavaScript speech synthesis with longer texts.

Use JavaScript Speech Synthesis with Longer Texts

To use JavaScript speech synthesis with longer texts, we can create a function to resume the utterance of the text.

Then we can resume the utterance when the start event is emitted.

For instance, we can write:

const text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
const utterance = new SpeechSynthesisUtterance(text);
window.speechSynthesis.speak(utterance);

const resumeInfinity = () => {
  window.speechSynthesis.resume();
  timeoutResumeInfinity = setTimeout(resumeInfinity, 1000);
}

utterance.onstart = (event) => {
  resumeInfinity();
};

utterance.onend = (event) => {
  clearTimeout(timeoutResumeInfinity);
};

We speak the text with:

const text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
const utterance = new SpeechSynthesisUtterance(text);
window.speechSynthesis.speak(utterance);

Then we create the resumeInfinity function which calls window.speechSynthesis.resume to continue speaking the text.

Then we create the timeoutResumeInfinity timer to call resumeInfinity after 1 second.

We call resumeInfinity in the onstart method so that the text is spoken until it reaches the end.

And in the onend method, we call clearTimeout with timeoutResumeInfinity to clear the timer.

Conclusion

To use JavaScript speech synthesis with longer texts, we can create a function to resume the utterance of the text.

Then we can resume the utterance when the start event is emitted.