Skip to content
Home » How to Use JavaScript Functions to Perform Calculations with Delay

How to Use JavaScript Functions to Perform Calculations with Delay

This blog post will guide you on using JavaScript functions to perform different calculations. Specifically, we will explore how to use a function that introduces a delay in the calculation process. By following this tutorial, you will be able to understand the concept of function implementation in JavaScript and how to create functions that perform calculations with or without delay.

Code

const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay))

const sumWithDelay = async (a, b) => {
  console.log("Delay started")
  await sleep(3000)
  console.log("Delay ended")
  return a + b;
}

const sum = async (a, b) => {
  return a + b;
}

const mul = async (a, b) => {
  return a * b;
}

let dne = async function() {
  return 'it does not exist';
};

let doCalculation = function(route) {
  switch (route) {
    case 'sum':
      return sum;
    case 'sumWithDelay':
      return sumWithDelay;
    case 'mul':
      return mul;
    default:
      return dne;
  }
};

doCalculation('sumWithDelay')(2, 2).then(res => console.log(res)); //4
doCalculation('sum')(3, 4).then(res => console.log(res)); // 7
doCalculation('mul')(3, 4).then(res => console.log(res)); // 12
doCalculation('dne')(3, 4).then(res => console.log(res)); // it does not exist

Code Explanation

The provided code snippet demonstrates the usage of different JavaScript functions for performing calculations. Let’s break down the code and explain each part.

1. Defining the “sleep” function:

The “sleep” function is implemented using a promise to introduce a delay in the execution of code. It takes a “delay” parameter and returns a promise that resolves after the specified delay using the “setTimeout” function.

const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay))

2. Defining the “sumWithDelay” function:

The “sumWithDelay” function showcases the usage of the “sleep” function. It starts by logging “Delay started” to the console, then awaits the “sleep” function, which introduces a delay of 3000 milliseconds. After the delay, it logs “Delay ended” to the console and returns the sum of the two passed parameters, “a” and “b”.

const sumWithDelay = async (a, b) => {
  console.log("Delay started")
  await sleep(3000)
  console.log("Delay ended")
  return a + b;
}

3. Defining the “sum” and “mul” functions:

The “sum” and “mul” functions are simpler in comparison. They accept two parameters, “a” and “b”, and return the sum and product of these parameters, respectively.


const sum = async (a, b) => {
  return a + b;
}

const mul = async (a, b) => {
  return a * b;
}

4. Defining the “dne” function:

The “dne” function stands for “it does not exist” and returns this string when called. It is assigned to a variable using the function expression syntax.

let dne = async function() {
  return 'it does not exist';
};

5. Defining the “doCalculation” function:

The “doCalculation” function takes a route as a parameter and utilizes a switch statement to determine the appropriate calculation to perform based on the route. It returns the corresponding function for the given route. If the route does not match any cases, it returns the “dne” function.

let doCalculation = function(route) {
  switch (route) {
    case 'sum':
      return sum;
    case 'sumWithDelay':
      return sumWithDelay;
    case 'mul':
      return mul;
    default:
      return dne;
  }
};

6. Performing calculations and logging the results:

The code snippet includes four function calls to “doCalculation” with different routes and values. These calculations demonstrate how to utilize the functions defined above to get the desired results.

doCalculation('sumWithDelay')(2, 2).then(res => console.log(res)); // 4
doCalculation('sum')(3, 4).then(res => console.log(res)); // 7
doCalculation('mul')(3, 4).then(res => console.log(res)); // 12
doCalculation('dne')(3, 4).then(res => console.log(res)); // it does not exist

In the first call, the “sumWithDelay” function is used to perform a calculation with a delay. This results in the sum of 2 and 2, which is 4.

In the second and third calls, the “sum” and “mul” functions are used to perform regular calculations without any delay. The sum of 3 and 4 is 7, while the product of 3 and 4 is 12.

Finally, in the fourth call, the “dne” function is invoked, resulting in the string “it does not exist”.

By understanding and implementing these code snippets, you can utilize JavaScript functions to perform various calculations, including ones with delays. This knowledge can be particularly useful when dealing with asynchronous operations and time-sensitive tasks.

Remember to test and experiment with different inputs and functionalities to gain a comprehensive understanding of how these functions work.

That’s it for this tutorial! Happy coding!

Also checkout the following codes.


Program to Check if a Value is an Object in JavaScript
How to Format and Group Refunds in JavaScript