Executing a function with arguments within a separate function

I've been working on creating a scheduler function that can randomly call another function with parameters. Here's the JavaScript code I have so far:

function scheduleFunction(t, deltaT, functionName) {

    var timeout;
    var timeoutID;

    function scheduler() {
      functionName()

      clearTimeout(timeoutID);
      timeout = Math.trunc(Math.random() * 2 * deltaT - deltaT) + t;
      timeoutID = setTimeout(scheduler, timeout);
    }

    scheduler();

  }

The function works perfectly when calling functions without parameters. For example:

function printSomething() {
        console.log("Printing something...");
      }

scheduleFunction(1000, 500, printSomething);

However, it doesn't support calling functions with parameters. An example of what I'm trying to achieve is:

function print(string) {
        console.log(string);
}

scheduleFunction(1000, 500, print("Hello World!"));

Is there a way to modify the scheduler function to allow for this type of functionality?

Answer №1

Try this technique for binding arguments:

scheduleFunction(1000, 500, print.bind(null, "Hello Universe!"));

function scheduleFunction(t, deltaT, functionName) {
  var timeout;
  var timeoutID;

  function scheduler() {
    functionName()

    clearTimeout(timeoutID);
    timeout = Math.trunc(Math.random() * 2 * deltaT - deltaT) + t;
    timeoutID = setTimeout(scheduler, timeout);
  }

  scheduler();
}

function print(string) {
  console.log(string);
}

scheduleFunction(1000, 500, print.bind(null, "Hello Universe!"));

Answer №2

Easy

executeTask(1000, 500, function() {
  displayMessage("Greetings Earthlings!")
});

Answer №3

When a function is executed, a special object variable called arguments is automatically added to the function's scope.

This object holds all the parameters that were actually passed into the function, regardless of what was originally defined in the function's definition. This means that you can access all passed parameters, whether there are more or fewer than expected.

With this knowledge, you can treat any parameters starting from the 4th argument that are passed to the scheduledFunction as the parameters to be used for calling the functionName. To achieve this, you can use Array#slice and Function#call (needed because arguments is not an array but an array-like object):

var args =  [].slice.call(arguments, 4);

You can then utilize Function#apply to invoke functionName and pass the sliced arguments as parameters:

functionName.apply(null, args);

The revised code would resemble the following:

function scheduleFunction(t, deltaT, functionName) { 
  var timeout; 
  var timeoutID;

  // Retrieve additional parameters (if any)
  // starting from the 4th one
  var args =  [].slice.call(arguments, 4);

  function scheduler() {
    // Call functionName with all extra parameters 
    functionName.apply(null, args);

    // Etc...
  }
  scheduler();
}

To use it, notice that print is no longer directly invoked, instead, the arguments follow it as parameters to scheduleFunction:

function print(string) { 
  console.log(string);
}

scheduleFunction(1000, 500, print, "Hello World!");

You can output multiple arguments by adjusting how console.log is called:

function print() {
  // No specific parameters defined BUT 'arguments' is available.

  // Convert it into a true array using slice
  var args = [].slice.call(arguments, 0);

  // Utilize Function#apply to call console log with
  // multiple parameters extracted from the args array
  console.log.apply(null, args);
}
scheduleFunction(1000, 500, print, "Hello World!, "Hello again!");

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 eliminate an object from an array using JavaScript?

I am currently working with two arrays named totalArray and selectionArray. These arrays have dynamic values, but for the sake of example I have provided sample arrays below. My goal is to remove objects from totalArray based on their id rather than inde ...

Having npm start is causing an error to be displayed

I am encountering an issue when I try to start 'npm' on my mean.js application. The error message is related to a missing file called '.csslintrc'. Below, I have included the terminal output as well as the snippet of code where the erro ...

Using asynchronous functions in JavaScript to push an array does not function correctly

Trying to update the users array by pushing the dirs, but for some reason the dir property remains blank in the console.log statement after this. Any suggestions? I know I could use a synchronous function, but a friend mentioned that synchronous functions ...

What is the best way to utilize both the YouTube API and jQuery in order to successfully transfer a video file

I am currently working on utilizing the Youtube DataAPI in order to upload a video to our website's YouTube account. Although I have been referring to the documentation for Browser-based uploading and following its provided examples, I am facing troub ...

ensure that only one option can be selected with the checkbox

Can someone help me with applying this code on VueJS? I tried replacing onclick with @click but it's not working for me. I'm new to VueJS, so any guidance would be appreciated! function onlyOne(checkbox) { var checkboxes = document.getElement ...

Issues with basic emit and listener in socket.io

I recently inherited an App that already has socket IO functioning for various events. The App is a game where pieces are moved on a board and moves are recorded using notation. My task is to work on the notation feature. However, I am facing issues while ...

Utilize the npm module directly in your codebase

I am seeking guidance on how to import the source code from vue-form-generator in order to make some modifications. As a newcomer to Node and Javascript, I am feeling quite lost. Can someone assist me with the necessary steps? Since my Vue project utilize ...

Tips for transferring JavaScript values to PHP through AjaxWould you like to learn how to

Let's set the scene. I'm currently facing a challenge in passing Javascript values to different PHP functions within my ajax code so that they can be properly displayed on the page. Here is the snippet of my code: $("[data-departmen ...

jQuery for Implementing Pagination Across Multiple Tables

As a novice in the world of JavaScript and jQuery, I am struggling with implementing pagination for multiple tables on a single page. My goal is to have several tables that can be paginated using one navigation system. However, all my attempts so far have ...

Problems with Atom's ternjs autocomplete feature

My project structure is as follows: https://i.sstatic.net/J9Pk4.png The content of .tern-project is: { "ecmaVersion": 6, "libs": [ "browser", "jquery" ], "loadEagerly": [ "/bower-components/d3/d3.js" ] } I attempted to change d3.j ...

Guide on developing and releasing a Vuejs component on NPM

I have been diving deep into vue lately and incorporating it into all of the projects at my workplace. As a result, I have developed various components, particularly autocomplete. Although there are plenty of existing options out there, none seem to fulfil ...

CKeditor does not accept special characters or diacritics in keywords

Recently, I came across a helpful code snippet for CKeditor that counts and ranks the most used words in a textarea. This feature is invaluable for generating SEO-keywords suggestions while writing articles. However, there is an issue with non-English char ...

Steps for showing an error prompt when input is invalid:

In my Vue 3 application, I have implemented a simple calculator that divides a dividend by a divisor and displays the quotient and remainder. Users can adjust any of the four numbers to perform different calculations. <div id="app"> <inp ...

In JavaScript, there is a missing piece of logic when iterating through an array to find

I am working on a solution to populate empty values when data is not available for specific months. You can view my progress on Plunker here: http://plnkr.co/edit/f0IklkUfX8tkRZrn2enx?p=preview $scope.year = [ {"month":"mar", "val":"23"}, {"month":"feb", ...

typescript scrolling location

In my Angular UI code, I have a component class that includes the following structure: app.component.html //... <div class="banner"> <p-dialog [(visible)]="displayCOI" styleClass="coiDialog" [contentStyle]=" ...

Can a jQuery/JavaScript script be run standalone?

I've got a bunch of HTML pages saved on my computer and I'm looking to create a JavaScript script that can extract specific text or elements from those pages. I found some jQuery code snippets on Stack Overflow that do what I need, but I'm n ...

Strategies for resolving the error "Cast to ObjectId failed for value"

<form action="" method="post"> <input type="password" name="password" placeholder="Type Your Password Here" required> <input type="hidden" name="user_id" value=&q ...

I'm feeling a bit lost on where to go next with this JavaScript

I've been working on a project in Python where I need to retrieve a file, store it in an array, and display a random string from the array on HTML. However, I have no experience with JavaScript and am unsure how to proceed. I suspect there may be an i ...

Multer can handle the uploading of various files from multiple inputs within a single form

I've searched everywhere on the internet, but I can't seem to find a solution that matches my specific issue. As someone new to Node.JS, I'm attempting to upload two different pictures using Multer from the same form. Here's what my for ...

Creating an HTML5 video tag with bearer authentication using a WebAPI: The ultimate guide

My ASP.NET WebAPI requires bearer authentication, and most of my requests towards the API follow this format: GET http://localhost:29080/api/v1/users/me HTTP/1.1 Host: localhost:29080 Connection: keep-alive Accept: application/json, text/plain, */* Origin ...