How to get the remaining time of a running AWS Lambda Function using Node.js

To get the remaining time of a running Lambda Function using Node.js, we will use the context object’s getRemainingTimeInMillis() function. This returns the number of milliseconds that the Lambda Function can still run before it times out.

Below is a simple code that fetches the remaining time inside a Lambda Function. I have set the timeout to be only 3 seconds, that is why the output is 2,999 milliseconds or approximately 3 seconds.

exports.handler = async (event, context) => {

  const remainingTimeInMillis = context.getRemainingTimeInMillis()

  console.log(remainingTimeInMillis)
};

Output


Converting the Remaining Time to Seconds

To change the remaining time from milliseconds to seconds, we simply divide it by 1000.

See the Javascript below to get the remaining time of a Lambda Function.

exports.handler = async (event, context) => {

  const remainingTimeInMillis = context.getRemainingTimeInMillis()
  
  const remainingTimeInSeconds = remainingTimeInMillis/1000

  console.log(remainingTimeInSeconds)
};

Output


Getting the Remaining Time until Lambda Function Times Out

In the code below, the goal is to keep on logging the remaining time every 1 second until the Lambda Function times out.

I set the Lambda Function timeout to 10 seconds and set the interval of getting the remaining time to every 1 second.

exports.handler = function (event, context) {

    const interval = setInterval(function () {

        const remainingTime = context.getRemainingTimeInMillis()
        console.log(remainingTime)

    }, 1000)

};

Output


We hope this helps you get the remaining time of your running Lambda Function using Node.js.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.