Error encountered: The function performance.now() cannot be executed because performance is undefined

I'm encountering a problem with the error

ReferenceError: performance is not defined
while attempting to use performance.now() for measuring the execution time of a function call:

export async function find(someId: string, ctx: context.IContext) {

      try {
        var t0 = performance.now();

        var res = someModel.find(someId, ctx.cookies);

        var t1 = performance.now();
        console.log("Call to find took " + (t1 - t0) + " milliseconds.");

        return res;
      } catch (err) {
        console.error(err);
        throw err;
      }
    }

Can anyone provide suggestions on how I could resolve this issue?

Answer №1

Although this question is tagged front-end, for those seeking a node.js solution (such as myself), remember to import the performance module from perf_hooks (which is included in node version 8.5 and above).

const {performance} = require('perf_hooks');
const t0 = performance.now();
...

Answer №2

When working with the 'perf_hook' module, it is essential to specify which construct you intend to use since it exports various entities like objects, functions, and constants. Specifically, you will require the performance construct. There are two ways to declare this:

const performance = require('perf_hooks').performance;

Alternatively,

const { performance } = require('perf_hooks'); //utilizing object destructuring

Answer №3

If you want to maintain type information, it's recommended to use the import statement instead of require when importing "performance" in TypeScript:

import {performance, PerformanceObserver} from 'perf_hooks';

const observer = new PerformanceObserver(items => items.getEntries().forEach((entry) => console.log(entry)));    
observer.observe({entryTypes: ['measure']});

performance.mark('start');
performance.mark('stop');
performance.measure('Measurement', 'start', 'stop');

Don't forget to include @types/node in your "dependencies" section of your "package.json" file.

This code has been tested with TypeScript 4 and Node.js 14.

Answer №4

Absolutely! Just like the responses above, you'll need to include this snippet of code:

const {
      performance,
      PerformanceObserver
    } = require('perf_hooks');

However, you can also execute performance.now() directly within your browser console or by navigating to the browser's source tab and selecting snippet without having to add the code mentioned previously.

To delve deeper into this topic, feel free to check out the following link:

https://nodejs.org/api/perf_hooks.html#perf_hooks_performance_now

Answer №5

My experience was on a brand new next.js project, just after completing the installation wizard and integrating apollo. The issue was resolved by updating NODE to the most recent version.

You can achieve this by using nvm use 18 or by including a .nvmrc file in your application.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to incorporate both an input button and an anchor tag in my code?

Here's the situation: <a> Content content content <input type="Submit" onclick="...."> </a> The issue is that when I click the submit button, it redirects to a different page instead of triggering the onclick event. ...

Issues with Javascript functionality in Internet Explorer and Google Chrome

Hello everyone, I'm experiencing an issue with a thumb image link swapping out on hover. Oddly enough, it seems to work perfectly in Firefox and Safari, but it's not showing up on IE and Chrome. As I am relatively new to Javascript, I may be over ...

Handling Exceptions in Node.js and Express

Having recently delved into the world of javascript and node, I've been working on creating an application using node.js and express. While I've implemented appropriate error callbacks in my code, there are instances where the node.js server abr ...

Animating all the numbers on a jQuery countdown timer

http://jsfiddle.net/GNrUM/ The linked jsfiddle showcases a countdown of 2 seconds, with only the numbers displayed. My goal was to explore: a) How can I incorporate animations into the JavaScript code so that the number changes in size, color, and positi ...

Encountering download issues with the FileTransfer API on Android while using Phonegap

I'm currently working on incorporating the FileTransfer API into my Phonegap App using Javascript. However, when I use the code below to call it, I encounter the following error: 01-24 00:36:10.495: I/Web Console(14802): Error: SyntaxError: Unexpecte ...

Keeping JSP current with changes made to files on the client side

Currently, I am tackling a project that consists of two main components: a) A Java Application that runs on a client machine. b) A Web Application that is hosted on a web server. The Java Application generates results at random intervals. These results n ...

The Keydown Event in Asp.net GridView may sometimes fail to be triggered

While working within a gridview on Internet Explorer, users can click on cells in one column to reveal a hidden textbox. After entering text into the textbox, users are instructed to press the Tab key to save changes. To accomplish this, a Javascript funct ...

angularjs select not chosen option

Hey there, I'm currently attempting to select an item from an array in the select options by using a string value. Below is my HTML code: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularj ...

Converting Dates to getTime() in AngularJS prior to server transmission

In my form, I am using <input type="datetime-local" ng-bind="course.endDate".. to set a model variable. Before sending the date to the server, I need to convert the date 2015-04-04T22:00:00.000Z to an integer using getTime(). In the controller, I added ...

Building and executing an Angular 2 program on the Windows platform: Step-by-step guide

After successfully installing npm and related packages including TypeScript and Angular 2, I am encountering difficulties running Angular 2 in my browser on a Windows platform. Can someone provide a step-by-step guide to help me create and run Angular 2 ...

Performing a search within an ElementArrayFinder

My journey of learning protractor has been quite an adventure, especially since I am relatively new to JavaScript. I have discovered that protractor queues all promises and they can be executed using then(). However, I am currently facing an issue with usi ...

Numerous subscribers utilize Angular 2 for handling HTTP requests

Working with data returned from an http post request in both a service and a page in Angular 2 can be tricky. The challenge arises when calling the service function this.Auth.login(), which initiates the http post request. Upon receiving the data from the ...

Tips for displaying an alert when the input value dynamically changes in jQuery

I am attempting to display an alert when the input value changes. I am using jQuery, so here is a demonstration of what I am trying to achieve but the alert is not showing or working. Thank you $(".d1, .d2").click( function (e) { var $this = $(this); $( ...

Limit the frequency of function calls in Typescript

Update: After some research, I've learned that throttle has the capability to drop excess function invocations, making it unsuitable for my needs. I am still seeking an idiomatic solution to process every item in a queue at an appropriate pace without ...

Using methods from one component in another with NgModules

There are two modules in my project, a root module and a shared module. Below is the code for the shared module: import { NgModule } from '@angular/core'; import { SomeComponent } from "./somecomponent"; @NgModule({ declarations: [SomeCompon ...

Ensuring a response is sent back only after a loop has completed in NodeJs

Struggling to properly format the logic in order to send back a fully populated array of objects after a GET request to a specific URL. The goal is to take the "connections" array from the user making the request, extract the connection's name and pic ...

Is it possible to create a horizontal bar graph featuring two different category axes?

I am a beginner with chart.js and I am attempting to create a horizontal bar chart with categories on both the x and y axes. While the axes are displaying correctly, I am unable to see any data on the chart. To troubleshoot, I switched to a line chart and ...

Instructions on adding an activity indicator in a centered box with a loader inside

I'm currently working on integrating an Activity Indicator into my Vue Native App, but I've been facing some issues as it doesn't seem to be displaying the Activity Indicator properly. Here is the code snippet I've tried: <Absolute ...

Ways to recycle code with similar functionality but varying variable names

I have 3 buttons that copy content from a text area. All three functions are the same, only the variable name changes. How can I combine these into a single function instead of having three separate ones? <div class="divclip"> <butto ...

I am interested in creating an input range slider using React and TypeScript

This code was used to create a slider functionality import { mainModule } from 'process'; import React, { useState } from 'react'; import styled from 'styled-components'; const DragScaleBar = () => { const [value, setV ...