I am encountering an error with setTimeout(): Timeout { _called: false }

I have been experimenting with creating a function that generates a random number and then adds 5 to it after a 3-second delay

This is what I have attempted:

const add5 = (randomNum) => {
         return randomNum + 5
}
// Function for you to get started with:
const generateRandomNumber = () => { 
    const rand = Math.round(Math.random() * 10);
    // ....
  console.log(rand)
 console.log(setTimeout(add5, 3000, rand))
}
generateRandomNumber()

Now, I am trying to log the results to observe the implementation in action. When I executed the code, I received the following result:

9
Timeout {
  _called: false,
  _idleTimeout: 3000,
  _idlePrev: 
   TimersList {
     _idleNext: [Circular],
     _idlePrev: [Circular],
     _timer: Timer { '0': [Function: listOnTimeout], _list: [Circular] },
     _unrefed: false,
     msecs: 3000,
     nextTick: false },
  _idleNext: 
   TimersList {
     _idleNext: [Circular],
     _idlePrev: [Circular],
     _timer: Timer { '0': [Function: listOnTimeout], _list: [Circular] },
     _unrefed: false,
     msecs: 3000,
     nextTick: false },
  _idleStart: 141,
  _onTimeout: [Function: add5],
  _timerArgs: [ 9 ],
  _repeat: null,
  _destroyed: false,
  [Symbol(asyncId)]: 7,
  [Symbol(triggerAsyncId)]: 1 }

Based on the changing random number value (9), I can conclude that the function is working as intended. However, I am puzzled as to why setTimeout() does not seem to be functioning as expected. Any insights or suggestions would be greatly appreciated.

Answer №1

Your code is currently logging the output of the setTimout function itself, but what you really want to do is log the return value from the add5 function.

const add5 = (num) => {
    return num + 5
}

const generateRandomNumber = () => { 
    const random = Math.round(Math.random() * 10);
    // ....
    console.log(random)
    setTimeout(r => console.log(add5(r)), 3000, random)
}

generateRandomNumber()

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

Discovering the Nearest Point to the Mouse Cursor using Three JS Ray Casting

Three.js version r85 While using raycasting in Three JS, a list of points is generated, and I am interested in identifying the point closest to the cursor. It appears that the first point returned is typically the one nearest to the camera. Is there a me ...

Is the CSS scale activated by mouseover or click?

My CSS code successfully scales images, but the issue is that it affects every image on the page. I am looking for a solution to apply this CSS only when the user hovers over or clicks on an image. The challenge is that images are added by non-technical w ...

refresh PHP automatically using JavaScript

Working on my Laravel application, there is a JavaScript function that I have defined: function abc(){ var x = '<?php ($user && ($user->first_name == "" || $user->number == "")) ?>'; } Upon initial page load, the variable ...

Have you ever wondered why a listener on the 'data' event interprets two separate requests as one, unless a timeout is added?

It seems that there is a tricky issue with node where it combines 2 different requests into one unless a timeout is added. In the code snippet below, if we write 'one' and 'two' to the server and push the result to an array, node interp ...

Encountering a problem with the state error while trying to modify an input field during onChange event

Whenever I pass state down from a parent component, the setState function keeps triggering an error that says setEmail is not a valid function on change event. Is there a simple solution to fix this issue? Every time I type a string into the email input f ...

Pairing TMDb genre IDs and their respective names using JavaScript within the Ember.js framework

If you've ever worked with the TMDb (The Movie Database) api for movies, you might have encountered this issue. I am struggling to display the genre names for each movie shown. My goal is to replace the numbers in genre_ids from the movies api with th ...

Show or hide text when list item is clicked

This is the rundown of services <div> <a href="#hig"><button class="tag-btn">High blood pressure Diabetes</button></a> <a href="#hih"><button class="tag-btn">High ch ...

Tips for showcasing a table generated from various input types on a separate page after pressing the submit button

After creating two JavaScript functions, I am eager to utilize both of them upon pressing the submit button on my form. The first function is already integrated into the submit button and activates a paragraph display upon submission. Now, I intend to sh ...

The function image.getState is not recognized (when trying to implement ol in an Angular project)

I attempted to integrate the code provided in an angular(4) application at the following link: However, I encountered an error every time I tried to launch the browser. To start with, here are my imports (both libraries were locally installed via npm): ...

Ways to integrate mouse out functionalities using an if condition

I'm currently working on a menu using Javascript where clicking on one option will dim the other options and reveal a sub-menu. I'm looking to include an if statement in the function so that when a user mouses out of both the sub-menu and the cli ...

What is the best way to stop the browser from automatically redirecting to another page after submitting a form?

I am using an AJAX call to a method that returns JSON data. How can I retrieve and read the JSON response without being redirected to a new empty page? [HttpPost] public JsonResult Test() { return Json("JSON return test", JsonRequestBehavior.AllowGe ...

Oops! Seems like I can't update headers once they have been sent in Node / Express

Currently working on a tutorial from the MEAN Machine book, specifically the chapter on route APIs. If you want to see the complete code, it's available here: https://gist.github.com/leongaban/6db44e513db4ca9e784f The code below shows how to fetch a ...

Transforming data structures into arrays using Javascript

Could someone help me with converting the following code snippet? const words = {told: 64, mistake: 11, thought: 16, bad: 17} I need it to be transformed into: const words = [ {text: 'told', value: ...

What is the best way to pick out specific passages of text

I'm attempting to create an autocomplete feature where the data is displayed in a div below the text box as the user types. While this typically involves ajax, I've simplified the approach without using jQuery autocomplete. Once the text appears ...

Javascript - formatting numbers with decimals

This question is not related to math or operators, but rather a formatting or masking issue. I am working on creating an order form that uses Javascript to tally and display the quantity and cost of each column in separate fields. I am trying to format th ...

What is the best way to transfer the userId from the browser to protractor?

Using *ngFor in my angular2 component to render users has been successful. <ul> <li *ng-for="let user of users"> <input [(ng-model)]="user.name"> <button (click)="remove(user._id)">Remove</button> ...

Ways to invoke a C# server-side function using JavaScript

I'm looking to invoke a C# server method from JavaScript. Within my gridview, there is a column containing dropdown lists. When the value of the dropdown list changes, I need to use JavaScript to call a server-side method and update the value of anoth ...

Having trouble initiating NPM in a terminal

I keep encountering an issue whenever I try to start NPM using a command in the terminal. Here is the error message that appears: npm ERR! npm ERR! Did you mean one of these? npm ERR! npm star # Mark your favorite packages npm ERR! npm stars # Vi ...

Is there a way to link to a specific section within a webpage using its ID, landing halfway down the page instead of at the top?

Can someone help me out with this issue? The header on my page is fixed at the top and has a height of 75px. When I click on a link (<a href="/company/#contact/">contact</a>), it takes me to the right section but the top part is hidden behind t ...

How to properly declare an explicit injector when using the resolve parameter in $routeProvider?

$routeProvider resolve feature in AngularJS allows for injecting additional dependencies to the controller function. How can we combine this with explicit dependency injection declaration? Example: angular.module('myModule', []) .config(func ...