Is there a way to automatically trigger a function once another function has completed its execution?

I am diving into the world of JavaScript as a beginner. All I want to do is trigger the function called seconOne() right after the execution of firstOne(). Specifically, I need the function two to be invoked when the value of p1 reaches 4. While I can use setTimeout() to achieve this by waiting a set amount of time before calling seconOne(), I am unsure about how many iterations it will take for firstOne() to complete.

 // Accessing DOM elements
const p1 = document.getElementById(`one`);
const p2 = document.getElementById(`two`);
const p3 = document.getElementById(`three`);

// First function
function firstOne() {
    for (let i = 0; i < 5; i++) {
        setTimeout(() => {
            p1.innerHTML = i;
        }, i * 1000);
    }
}

// Second function
function seconOne() {
    for (let i = 0; i < 5; i++) {
        setTimeout(() => {
            p2.innerHTML = i;
        }, i * 1000);
    }
}

Answer №1

One potential resolution is to utilize promises. For further insights on promises, check out this resource.

Example in Action

var p1 = 1;
var p2 = 2;
var p3 = 3;

const firstPromise = new Promise((resolve, reject) => {
  for (let i = 0; i < 5; i++) {
        setTimeout(() => {
            p1 = i;
        }, i * 1000);
    }
  resolve()
 
});

const secondPromise = new Promise((resolve, reject) => {
  for (let i = 0; i < 5; i++) {
        setTimeout(() => {
            p2 = i;
        }, i * 1000);
    }
    resolve()
});


//execute the first promise
console.log("First promise called")
firstPromise
  .then((response) => {
    console.log("First promise done")
    
    //execute the second promise once the first one succeeds
    console.log("Second promise called")
    secondPromise
      .then((response) => console.log("Second promise done"))
  })

Answer №2

Don't worry, your question is perfectly valid. To delve deeper into this topic, you should familiarize yourself with callbacks and promise handlers. These concepts essentially instruct JavaScript to pause execution until a specific task is finished.

executeTask1().then(() => executeTask2())

Answer №3

Ensure to include an if statement within your primaryOne function.

const element1 = document.getElementById(`one`);
const element2 = document.getElementById(`two`);
const element3 = document.getElementById(`three`);

// primary function
function primaryOne() {
    for (let num = 0; num < 5; num++) {
        setTimeout(() => {
            if(num == 4){
               secondaryOne();
            }else{
                element1.innerHTML = num;
            }
        }, num * 1000);
    }
}

// secondary function
function secondaryOne() {
    for (let num = 0; num < 5; num++) {
        setTimeout(() => {
            element2.innerHTML = num;
        }, num * 1000);
    }
}

Answer №4

Expanding on the suggestions provided by others to utilize a Promise, here is a more versatile approach that incorporates async/await as well.

(To summarize: calling a function with a count and an element will result in a promise indicating that work will be completed "at some point". An inner function iterates through updating the element's content until the specified count is reached, at which point the promise resolves, allowing the next task to commence).

// Select and store the elements
const p1 = document.querySelector('#one');
const p2 = document.querySelector('#two');
const p3 = document.querySelector('#three');

// Define `timer` function which takes count and element
function timer(count, el) {

  // Return a promise stating:
  // after completing this work, resolve,
  // enabling the event queue to proceed
  return new Promise(resolve => {

    // Create a loop to update numbers
    // in the element up to the specified count.
    // Once count is reached, resolve the promise
    function loop(n = 0) {

      // If current `n` value is <= count
      if (n <= count) {

        // Update element content
        el.textContent = n;

        // Call `loop` again after one second
        // with an incremented `n` value
        setTimeout(loop, 1000, ++n);

      // Otherwise, resolve the promise
      } else {
        resolve();
      }

    }

    loop();

  });
}

// Await each resolved promise
async function main() {
  await timer(4, p1);
  await timer(7, p2);
  await timer(20, p3);
  console.log('Done!');
}

main();
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>

For further information, refer to:

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

Is it possible to extract content from a remote website by utilizing javascript and iframe?

Are there any resources available for working with iframes in Ruby on Rails? **UPDATE:** I have a link that directs to an external website. I am looking to extract the content from that site and save it within my application. Is this achievable without re ...

How can we utilize CSS floats to achieve maximum widths?

I currently have 5 divs that I need to structure in a specific way: Each div must have a minimum size of 100px The parent container should display as many divs as possible on the first row, with any remaining divs wrapping to new rows if necessary If the ...

The instance cannot be accessed by ES6 class methods

Having trouble accessing the this instance in one of my methods within a class that I created. In my router, I am calling the method like this: import Emails from '../controllers/emails' import router from 'express' .... route.post(&a ...

Utilizing asynchronous functions to assign a JSON dataset to a variable

Having an issue here! I've created a function to retrieve data from a local JSON file on my server. The problem is that the data is returned asynchronously, so when I try to set it to a variable for later use, it always ends up being undefined. I don& ...

Tips for setting NgForm value within an Observable and verifying its successful implementation

Exploring the functionality of NgForm, I am testing to validate if the value of a form gets updated when the state of the store changes. @ViewChild('form') form: NgForm; ngOnInit() { this.subscription = this.store.select('shoppingList&apos ...

Steps to make a pop-up window for text copying by users

On my website, I have a link that users need to copy for various purposes. I want to provide an easy way for them to see the link and then manually copy it to their clipboard. Instead of using code to copy to the clipboard, I am looking for a solution whe ...

Code for object creation, inheritance, and initialization

In the code snippet below, a class is defined for managing input events such as mouse, touch, and pointer: // base.js export default () => { return { el: undefined, event: undefined, handler(ev) { console.log('default handler&a ...

Deactivate a button on a specific tab

My setup includes two tabs: <div class="modal-body"> <form name="myForm" novalidate="novalidate"> <ul class="nav nav-tabs"> <li class="active"><a data-toggle="tab" href="#basicInfo">Info</a></li> ...

The onChange method in React is failing to execute within the component

I am having trouble overriding the onChange method in a component. It seems like the method is not triggering on any DOM events such as onChange, onClick, or onDblClick. Below are the snippets of code where the component is rendered and the component itsel ...

jQuery is not updating the div as expected

While typing out this question, I'm hoping to uncover a solution that has eluded me so far. However, just in case... About a year ago, I successfully implemented something similar on another website and went through the code meticulously. Surprisingl ...

The data remains stagnant even after employing the onDataChange function in react native following the integration of a reusable component

My reusable Text input component is not working properly for validation. I am unable to retrieve the input value as it always shows null. This is how I am retrieving the username and password: <LoginTextBox placeholderName='Email& ...

Adjusted position of the viewport if the DOM element containing the renderer is not located at the top of the display

I've come across an issue with a three.js scene within an Angular custom directive in the view. At the top, there's a navigation bar for switching between views (pretty standard so far). I set up a simple scene with a cube and basic camera rotati ...

Is it possible to encase <v-img> within an anchor element?

I am currently using Vuetify 1.5 and have included a couple of <v-avatars></v-avatars> elements in which there is a nested <v-img></v-img>. I attempted to enclose the img tags within an a tag but encountered an issue wherein the ima ...

I am currently working on a website that offers different themes, and I am attempting to update the iframe to reflect the selected theme on the site

I'm feeling lost on how to accomplish this task. Despite my efforts, I have been unable to find a solution so far. Perhaps utilizing javascript might be the key here, yet I am uncertain about integrating it into the existing script that I use for modi ...

Trigger a function post-rendering in a React component

Hey everyone, hope you're having a great day! I've been diving into React for a few months now. I'm making an effort to steer clear of using the traditional React Components, opting instead for React Hooks. However, there are instances wher ...

Create a path on the Google Map that follows the designated route

I am looking for a solution similar to one found here: Sample However, I have been unable to find a suitable solution anywhere. The main issue is being able to follow the route in order to draw a line between two points. Can anyone provide guidance on ho ...

Adding color to characters, digits in an HTML file

Is it possible to individually style each letter, number, and symbol in an HTML document with a unique color? I am interested in creating a text editor that applies specific colors to each glyph for those who have grapheme-color synesthesia. While there ar ...

Image-switching button

I'm new to JavaScript and struggling with my first code. I've been staring at it for two days now, but can't figure out what's wrong. The goal is to create an HTML page where the user can change an image by clicking on a button, and th ...

Accessing the value of a hidden field within an ng-repeat loop when binding to an HTML table

I am working on a project where I have an HTML table with data being bound from AngularJS. The structure looks something like this: <tr ng-repeat="item in List| filter: { MachineType: 'Physical' }"> <td>{{item.MachineType}}< ...

Using jQuery to add a checkbox to a list that is not ordered

My HTML structure includes an unordered list with nested lists. Here is a snippet of the code: <div id="checklist"> <ul> <li>On Page SEO <ul> <li>My work <i>And note.</i>< ...