Ensure that the code runs only once another method has completed its execution

My goal is to have a function called setSource perform an action that takes about 3 seconds to complete.


editor.setSource();

setTimeout(function () {
   // Execute additional commands
}, 3000);

I need the section of code labeled "//do something, some commands" to run after the setSource() function has finished executing. Currently, I am achieving this using setTimeout, but I recognize that it may not be the most optimal solution as setSource() could potentially take longer than 3 seconds to execute. How can I ensure that these commands run only after setSource() has completed its task?

Answer №1

Implement a callback function for setSource:

editor.setSource = function(callback) {
    // perform editor tasks
    callback();
}

Pass the next block of code as a callback:

editor.setSource(function() {
    // do additional tasks
});

If jQuery's deferred objects are available, utilize them in this manner:

  1. Create a new deferred object.
  2. Initiate a timeout to execute lengthy tasks.
  3. Return the deferred object.
  4. In the timeout, upon task completion, call deferred.resolve.

 

editor = {
    setSource: function() {
        var deferred = $.Deferred();

        console.log("Beginning editor.setSource...");

        setTimeout(function() {
            // Task taking significant time
            deferred.resolve();
        }, 3000);

        return deferred;
    }
}

$.when(editor.setSource()).then(function() {
    console.log("Editor is done!");
});

If working with AJAX or animations using jQuery deferred objects already, directly return its result value instead of creating a new deferred object:

editor = {
    setSource: function() {
        return $.get({
            url: "myurl.com/mypage",
            data: $("#myform").serialize()
        });
    }
}

$.when(editor.setSource()).then(function() {
    console.log("Editor is done!");
});

Ensure understanding of handling either resolve or reject deferred objects effectively.

Answer №2

This solution utilizes promises, a component of the ECMAScript 6 specifications. If your desired platform does not natively support promises, you can implement them using PromiseJs.

In more recent browser versions, you have the option to leverage ES6 promises. The editor.setSource() function encapsulates its actions within a Promise, enabling further processing with additional functions.

editor.setSource = function(){
    return new Promise(function(resolve, reject){
        //perform necessary tasks
        resolve(resultValue);
    });
};

To chain it with another function, you can employ the then method on the promise.

var promise = editor.setSource();
promise.then(function(result){
    //perform additional actions
});

Answer №3

I ran into a situation where I needed my second function to run only after the first function had completed its execution. I experimented with callback functions, but couldn't find a suitable solution. Eventually, I discovered a simple way to resolve this issue using the $.ajax({ }); method code, which worked perfectly for me :).

For instance,

$.ajax({
  url: function1(),
  success: function(){
    //function 2 code here or simply call function2() here
  }
}); 

That's all! In this code snippet, the 'url' parameter will execute the first function, and the second function will only be called upon successful completion of the first one.

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

Picture in a clear background without any alteration

Is there a way to create a background-color with opacity inside an image without affecting the image itself? The issue lies in the fact that the transparent background-color makes everything underneath it, including text and the image, transparent. Below ...

Reorganizing a list in AngularJS after adding a new item

I have made edits to the AngularJS ordering example in my Plunker. The ordering works fine initially, but when I add a new person using code to periodically update the list of contacts, the new person gets added to the bottom without re-sorting. Is there a ...

Polymorph 1.0 - Using CSS Class Binding for Dynamic Properties

I attempted to link a CSS Class to a paper-progress element using the value of my property to change the item's color. I referenced Polymer's example on GitHub and studied the documentation on Data-binding. Here is my code: http://jsbin.com/bide ...

What is the best way to extract every nth digit from a number using a given reference point?

The subject of the title may cause confusion, so let me clarify my goal. With values of n = 51 and m = 24, I aim to achieve this result: [ {start:0, end:24}, {start:24, end:48}, {start:48, end:51} ] Currently, I have made progress on this ...

Avoid having to refresh the page on create-react-app after uploading an image or file

Currently, my application is set up with 'create-react-app' and I am retrieving images from a folder within the 'src' directory. However, when a new image is uploaded through a form submission, it causes the page to reload as the image ...

I'm experiencing a problem with my React application where errors are not being shown in the browser. Instead

https://i.sstatic.net/FTMz7.png Why is React only displaying an empty screen instead of showing errors like on my instructor's system? https://i.sstatic.net/QCbgG.png How can I resolve this issue? EDIT: While I can see the error in the console and ...

Creating a stylish Go URL bar using HTML and CSS

Looking for some guidance in JavaScript as I am new to it. I want to create a go bar similar to the ones found at the top of browsers using HTML and JS. When the button is clicked, it should navigate to the URL entered in the box. Here's an example of ...

What is the best way to arrange an array of objects based on a specific attribute?

Ordering object based on value: test": [{ "order_number": 3, }, { "order_number": 1, }] Is there a way to arrange this so that the object with order_number 1 appears first in the array? ...

The Angular promise refuses to resolve at my desired time

I am struggling with managing Angular promises in order to control when they resolve. In the code snippet below, my intention is to first retrieve KeyDataFromServer() and then proceed with executing the remaining commands only after all the keys have been ...

Loading screen for specific content within the current WordPress theme

I am trying to display a preloader only in the 'content' div, but it ends up hiding the entire page. The structure of the site is as follows: Title Menu Content (where I want the preloader) Footer I'm having trouble figuring out where exa ...

Fetch Timeout Issue in React Native

I am currently using fetch to retrieve data from a server. Unfortunately, I am facing issues with setting a timeout for the fetch request in case the server does not respond. This is my global fetchData class: fetchGetResp(url, token) { return fetch( ...

Marionette - Apply a class to the parent ItemView's tagname

I've been working with Bootstrap accordion panels and I'm trying to assign a class to the parent panel of the panel-collapse. Essentially, what I want to achieve is: if (child element) hasClass('panel-collapse.in') { this.addClass ...

The optimal approach for AngularJS services and promises

I have a unique setup in my AngularJS application where I utilize services to make API calls using $http and handle promises in my controllers. Here's an example of my current approach: app.service('Blog', function($http, $q) { var deferr ...

Having trouble getting rid of the border-bottom?

I have been attempting to customize the appearance of the React Material UI tabs in order to achieve a design similar to this: https://i.stack.imgur.com/tBS1K.png My efforts involved setting box-shadow for the selected tab and removing the bottom border. ...

What is the best way to determine if my code is executing within a NodeJS environment?

I am working on a piece of JavaScript code that is specifically meant to run in NodeJS. It uses functions like require(), so running it elsewhere would cause errors. I want to add a runtime check to ensure the code is only executed within NodeJS and displa ...

Trouble in Cypress Automation: Unable to locate button using text-based search

Recently, I have been diving into learning Cypress and have spent the last few weeks automating different websites. However, I have encountered a challenge when trying to click a button based on its class or text value, which seems like it should be a simp ...

When utilizing useMachine in TypeScript, an error is thrown regarding incompatible types

While attempting to build my first example for a xstate finite machine by following the example on github.com/carloslfu/use-machine, I encountered a TypeScript error that halted my progress: Argument of type '{ actions: { sideEffect: () => void; } ...

Add a unique CSS style to both text and image using anchor tags

Why isn't the hover effect of color transition and underline being applied to the image? It seems to only work for text. While I understand that the color transition may require a change in image color, shouldn't the underline still occur? This ...

The npm install command failed due to a lack of suitable versions for pinkie-promise

I am currently attempting to perform a straightforward "npm install" from one of the repositories mentioned in a tutorial provided here Below is the content of the package.json: { "name": "react-playlist", "version": "1.0.0", "description": "A basi ...

How would the input value change if the clock time changed?

I am working with dynamic inputs that allow me to add and delete rows with inputs. These inputs include material-ui timepickers, which have an icon of a clock next to the input field. When I click on the clock icon, a clock widget appears. However, the val ...