Please hold off until the function has finished executing

With some guidance from a previous discussion, I've successfully implemented a code that waits for 3000ms and then sets a variable to 1. Subsequently, a loop is triggered every 1000ms to check if the variable has changed, and an alert is displayed when it does.

var myvalue;

setTimeout(function() {
  myvalue = 1;
}, 3000);

function check() {
  if (myvalue == 1) {
    alert("Value Is Set");
  } else {
    setTimeout(check, 1000);
  }
}

alert("debug1");
check();
alert("debug2");

The issue I'm facing now is that the execution doesn't wait for the completion of the check() function before proceeding. Upon adding some debug alerts, I noticed that they all fire simultaneously.

Is there a way to make it wait without relying on a timeout?

Answer №1

You have the option to provide a callback function and invoke it once the task is completed successfully.

For example:

var result;

setTimeout(function() {
  result = 1;
}, 3000);

function verify(callback) {
  if (result == 1) {
    alert("Result Has Been Set");
    callback && callback();
  } else {
    setTimeout(verify, 1000, callback);
  }
}

alert("debugging1");
verify(function() {
  alert("debugging2");
});

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

Struggling to display the preloader animation while waiting for the render.com server to start up (using the free tier web service)

My choice for deploying dynamic websites is render.com and I am currently using their free tier. The issue with this free service is that Render spins down the web service after 15 minutes of inactivity, resulting in a delay when it needs to spin back up u ...

Including a cancel button to close the open window

var messagebox = Ext.widget("messagebox", { target: grid, progressMessage: "Loading" }); The message box displayed above indicates the loading progress bar that appears when the download button is clicked. I am looking to incorporate a cancel button i ...

The configuration for the 'proxy' is all good and properly set

image description While trying to install the npm package "pdf-node", I encountered an error: Error: ENOTFOUND - getaddrinfo failed for . This seems to be a network connectivity issue. To resolve this error, make sure your network settings are configure ...

Is there a way to compare the values of two arrays of objects and conceal something if a match is found?

I am currently working on a task that involves checking if the values of one array of objects exist in another array of objects. The goal is to disable a table row if the values match. Below are the two arrays of objects I am working with. const array1 = ...

Utilizing a universal search feature for enhanced filtering in react-table : Boosting efficiency with React and react-table

I am currently working on implementing a global search filter that can search for a specific key throughout the entire table. I have set up a change handler that triggers a callback function every time there is an input, which in turn searches for the spec ...

Manipulating CSS styles with jQuery

Trying to update the UL image in the CSS directory using jQuery for a Twitter stream: as tweets are displayed, want to change the avatar of the account associated with each post. Using .css is straightforward, but struggling to modify the URL for the new i ...

Having trouble syncing a controller with AngularJS

Despite numerous attempts, I am still struggling to make a single controller function properly. Lately, I've been working on Angular projects and no matter what I do, my controllers just won't cooperate. In my latest project, everything is withi ...

Understanding the response from an AJAX call

VB code Dim temp3 As String = dt.ToString() cmd.Connection = con con.Open() i = cmd.ExecuteNonQuery() con.Close() If i = 1 Then msg = "Record successfully inserted" ...

The Discord.js bot is unable to send messages in embedded format

I created a Discord bot using discord.js with multiple commands, including three commands with embed forms. One command, "help", works perfectly fine, but the other two are not functioning properly. All of them have the same main code structure, specifical ...

Is there a way to show information exclusively on the selected card upon clicking?

[click here to see image 1] https://i.sstatic.net/cfvUT.png [click here to see image 2] https://i.sstatic.net/ISXAU.png Greetings, fellow beginners! Once again I find myself stuck on a coding problem. I have fetched various workout data and displayed t ...

Easily automate button clicks on a new tab website

Seeking assistance below, following codes are sourced from "example.com" as assumed: <a href="http://www.example.org" target="vo1" onclick="gp(1)" rel="nofollow">Click Me</a> Upon clicking on ...

What is the best way to retrieve data obtained through a node module and incorporate it into my HTML code within NodeWebkit?

I've been working on developing an app with NodeWebkit and utilizing the node-phantom-simple module for content scraping. While I have successfully scraped content from a website, I'm now wondering how I can access this data on the HTML side with ...

Add the latest value to the end of the selection option

How can I append a new value at the end of an option select box, ensuring that the number continues instead of starting from 1? var n_standard = 1; function removeStandard() { var select = document.getElementById('selectBoxStandard'); for ...

The Backbone Model is producing unspecified data

Having crafted a backbone model, it looks like this: var note_model = Backbone.Model.extend({ default : { HistoryKey : "", InsertDate : "", MemberKey : "", NoteDate : "", ContactNote : "", User ...

Error: The function getOrders is not defined in the customerFactory

Throughout my third attempt at learning AngularJS, I've hit a roadblock. I could really use some assistance as I keep encountering the error TypeError: customerFactory.getOrders is not a function. Despite thoroughly checking for typos, I haven't ...

Enhancing response accuracy with Prisma queries in Nest Js

Server-Side Logic: const studentAssignments = await this.prisma.classesToStudents.findMany({ where: { studentId: +studentId, classStatus: 'completed', }, select: { classes: { select: { projects: { ...

Developing a React Native application that utilizes TextInput components with both local state management

While typing on the keyboard, I encountered warnings indicating that the input was ahead of the JS code. The Native TextInput in React Native is 4 events ahead of JS - optimizing JS performance is crucial. To address this issue, I implemented the deboun ...

Adjust the size of icon passed as props in React

Below is the component I am working on: import ListItemButton from '@mui/material/ListItemButton'; import ListItemIcon from '@mui/material/ListItemIcon'; import Tooltip from '@mui/material/Tooltip'; const MenuItem = ({data, o ...

Angular's innerHTML dilemma

Within my Angular service, I have implemented three methods as shown below: public loadLiveChat() { let url: string; url = this.appConfig.config.liveAgent.liveAgentScriptUrl; this.dynamicallyLoadScript(url); ...

Error: Unable to access attribute 'item_name' as it is not defined

I'm new to React.js and I'm attempting to build a todo app. The main feature is a text input field where users can add items to their list. When I run "npm start," the app works perfectly and displays the expected output on my designated port. Ho ...