Is there a way to execute a javascript function using a thread or task?

I attempted the code snippet below:

.cs

    string someone = "John";
    int timer = 3000;
    int check = 1;
    string script = "<script> runPromise('" + someone + "'," + timer + "," + check + ").then(someone => { console.log('" + someone + "', someone)});</script>";
    ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", script);

.aspx

<script>
    let runPromise = (someone, timer, check, success = true) => {
        console.log(`${someone} start run`);
        console.log(check);
      return new Promise((resolve, reject) => {
        if (check == 1) {
          setTimeout(function () {
            resolve(`${someone} run ${timer / 1000} second`);
          }, timer);
        } else {
          reject(`${someone} fail`)
        }
      });
    }
</script>

This specific code is only functional within a button setting.

Is there a way to utilize this in a thread or task scenario where I need to wait for around 10 seconds?

Any assistance on this matter would be greatly valued.

Answer №1

why not try invoking the promise using a setTimeout

Modified

string person = "Jane";
int time = 15000;
int flag = 0;
string script = "<script> setTimeout(() => someFunction(('" + person + "'," + time + "," + flag + ").then(value => {console.log(value);}), " + time + ");</script>";
ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", script);

var someFunction = (person, time, flag) => {
  console.log(`${person} is starting execution`);
  console.log(flag);

  return new Promise((resolve, reject) => {
    if (flag == 1) {
      resolve(`${person} executed for ${time / 1000} seconds`);
    } else {
      reject(Error("Something went wrong"));
    }
  });
};

example:

var someFunction = (person, time, flag) => {
  console.log(`${person} is starting execution`);
  console.log(flag);

  return new Promise((resolve, reject) => {
    if (flag == 1) {
      resolve(`${person} executed for ${time / 1000} seconds`);
    } else {
      reject(Error("Something went wrong"));
    }
  });
};

setTimeout(() => someFunction(`someone`, 15000,1).then(value => {
console.log(value);
}), 15000);

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

Transfer a JSON object to a Java Class without relying on a servlet

I have a form in HTML where I collect user input and store it as an object in JavaScript. Here is how I am creating the object: var dataObject = { Name: getName(), Age : getAge() } Now, I want to send this object using Ajax to a b ...

Protractor: Decrease the magnification

Currently, I am working with protractor and facing the challenge of zooming out to 50%. Despite trying numerous solutions found on StackOverflow, none have successfully resolved the issue. Some attempted solutions include: browser.actions().keyDown(protra ...

Vuex: Clearing all data from the store and setting it back to an empty array

My Vuex store has a state variable called scannedList, which is initially set to an empty array []: state: { scannedList: [] } I have a mutation that adds ids to this array. I attempted to clear the entire state by using: store.commit('addToScann ...

What is the best way to replicate a synchronous ajax call? (mimicking synchronous behavior with asynchronous methods)

Given that a "native" synchronous ajax call can block the user interface of the browser, it may not be suitable for many real-world scenarios (including mine). I am curious to know if there is a way to mimic a synchronous (blocking) ajax call using an asy ...

What is the best way to customize the scroll bar of a Vuetify v-data-table?

Currently, I am working with a Vuetify v-data-table and I am interested in customizing the scroll bar of the data table. The current look is as seen here: https://i.sstatic.net/0GDXW.png Is there a way for me to style it according to my preference? ...

Why is it that methods lose their binding when they are returned from a ternary operator?

class TestClass { constructor() { this.prop = 5; } MethA() { console.log(this); console.log(this.prop); } MethB() { (true ? this.MethA : null)(); } } Test = new TestClass(); Test.MethB(); What is the ...

having trouble with if and else if statements functioning properly

After testing my code, an issue arises with the second else if statement. When both divs are active, only the class of #project-wrapper is removed. I suspect there may be an error in how I wrote the second else if condition. Can you help me spot any mist ...

Issue with Document Map in Report Viewer when exporting to Word in Office 2010

I'm having difficulties with the Export Option in Report Viewer (2012). Whenever I bind a column with Document map and group that column for a collated data view, I encounter gibberish in my Word document export for that collated row. Interestingly, i ...

Tips for resolving the error message "cannot find module './node'" when compiling with pkg:

After successfully running my Node.js script with 'node main.js', I encountered an error when trying to compile it into an executable using pkg: pkg/prelude/bootstrap.js:1876 throw error; ^ Error: Cannot find module './node' Require s ...

What is the best method for linking JavaScript to Python while exchanging data in JSON format bidirectionally?

I am currently exploring methods to establish a local connection between a Python server and a Javascript client by utilizing JSON format for the retrieval of data. Specifically, I aim to execute queries on the HTML client side, transmit these queries to t ...

Tips on avoiding page refresh when hitting the submit button:

I am working on a form that consists of one input field and one submit button. <form method='POST' action='' enctype='multipart/form-data' id="form_search"> <input type='hidden' name="action" id="form_1" va ...

Concealing content to prevent it from being accessed through HTML and JavaScript inspection techniques

I created a website with a simple guessing game where users can win if they enter the right code. My approach involves using JavaScript: <script> function z() { var b = document.getElementById('idea'); var a = document.g ...

retrieve the current image source URL using JavaScript

In the template below, I am looking to extract the current img src URL and utilize it in a fancybox button. For example, in the template provided, there are 3 images from https://farm6.staticflickr.com. When clicking on these images, the fancybox will ope ...

Validate the checkbox with Vuelidate only when the specified property is set to true

I have a website login form where users may need to check a specific checkbox before logging in. Here is part of the Vue component code that handles this functionality: <script setup lang="ts"> import {ref, defineProps} from 'vue&a ...

The issue is that AngularJS deferred.reject function is not functioning properly, while the $q

I'm struggling to understand the difference between Angular JS deferred and $q. I recently came across this SO Question that delves into the variance between $q.defer() and $q. According to the post: $q.reject serves as a quick way to create a defe ...

Combining Array Attributes to Create a New Property as a 'JSON String'

I'm attempting to combine the attributes of an array into a JSON-like string as a new attribute. For example: [{ { "orderNo":"1", "description":"Item 1", "note": "Note 1" }, { "orderNo":"2", "description":"Item 2", ...

Node.js utilized for conducting anti-virus scans on server-bound files prior to uploading

Is there a way for me to scan files that are submitted as request payloads to check if they contain potential viruses? For example, if someone tries to upload a txt file with the EICAR virus signature, I want to be able to scan it and reject it if it is in ...

Removing a particular word from a string output using substring index in C#

I encountered an error with data type conversion. System.FormatException: The string '11 ICU ECLH' was not recognized as a valid DateTime. There is an unknown word starting at index '3'. at System.DateTimeParse.Parse(ReadOnlySpan`1 s ...

Avoiding repetitiveness in AngularJS

I have 8 controllers using 12 common functions, but each controller has 3-4 unique functions. How can I avoid repeating myself in each controller while still utilizing a common service? Here is an example of my current code: app.controller("ArticleControl ...

How can I detect a DOM element mutation based on a CSS selector, and if this is possible, how can it be accomplished?

Imagine there's a website with a specific HTML element. It seems that this element has the same class during the DOMContentLoaded event as it does during the load event. However, after the load event, this class (and possibly the ID and other HTML att ...