Executing async functions in a specific order with Typescript

I am currently in the process of developing a custom YouTube player service using Angular 2. The main objective of this service is to offer two distinct methods:

  • playRange – This method enables playing a specific segment within a video, and then automatically skipping to a designated time once that segment ends. The range parameter consists of an array [start, end, returnTime]. To accurately pause the video at the specified time, I utilize setInterval to continuously monitor the video's current position, thereby making this method asynchronous.
  • playScript – With this method, users can play through a script, which is essentially an array of multiple ranges. Essentially, it allows for playing various segments consecutively in a predetermined sequence.

A snippet showcasing the implementation of the playRange method:

playRange(range: any) {
    if (this.player) {
      console.log('Playing range:' + range)
      const start: number = +range[0];
      const end: number = +range[1];
      const returnTime: number = range.length === 3 ? range[0] : range[2];
      this.player.seekTo(start, true);
      clearInterval(this._rangeTimer);
      if (this.player.getPlayerState() !== YT.PlayerState.PLAYING) {
        this.player.playVideo();
      }
      this._rangeTimer = setInterval(() => {
        const currentTime = this.player.getCurrentTime();
        if (currentTime >= end) {
          this.pause();
          clearInterval(this._rangeTimer);
          this.player.seekTo(returnTime, true);
        }      
      }, 200);
    }
  }

Now, I am looking for guidance on how I can effectively implement the playScript method to iterate through a series of ranges and play them sequentially. Any suggestions?

Answer №1

I'm not entirely clear on the inner workings of your logic, but I believe this high-level overview should provide some guidance. Take a look at it here:

type RangeArray = [number, number] | [number, number, number];

function playRange(range: RangeArray): Promise<void> {
    return new Promise<void>((resolve, reject) => {
        // Implement any necessary steps to play the range.
        // Once you've determined the range has finished, call resolve
        resolve();
    });
}

async function playScript(ranges: RangeArray[]):Promise<void> {
    while (ranges.length > 0) {
        await playRange(ranges.pop());
    }
}

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

Efficiently setting up the system-config.ts to incorporate additional libraries such as angular2-material2 package in Angular2

I'm feeling a bit lost trying to understand the configuration of system-config.ts. Currently, I am attempting to integrate material2 code into my Angular quick start bundle, but I'm facing some issues. On the material2 GitHub page, it instructs ...

Angular modal not responding to close event

My issue is that when I try to close a modal by pressing the X button, it doesn't work. Here is the button where I am triggering the modal: <button type="submit" id="submit-form" class="btn btn-primary" (click)="o ...

Utilizing a constant in setting the slotLabelFormat

I am attempting to configure the slotLabelFormat options in a React TypeScript project When I directly set slotLabelFormat={{ hour: "2-digit", minute: "2-digit", omitZeroMinute: false, meridiem: "short" }}, TypeScript compile ...

Definition of a class in Typescript when used as a property of an object

Currently working on a brief .d.ts for this library, but encountered an issue with the following: class Issuer { constructor(metadata) { // ... const self = this; Object.defineProperty(this, 'Client', { va ...

Unable to transfer information between two components using a service if the recipient component has not been initialized

I am facing an issue with passing data from an admin component to an edit component in my project. I have set up an Edit Service for this purpose, but I'm struggling to retrieve the data when the Edit component is loaded. In the admincomponent.ts fil ...

The error message "Unable to access property MyToast.java as it is not

I've been diligently following this tutorial on how to write Java code in NativeScript and use it directly in TypeScript. But, unfortunately, I encountered an error message stating: Cannot read property 'MyToast' of undefined app.component ...

RxJs: Generating an observable based on changes in a field's value

Is there a way to generate an Observable using the variable this.pending as its source? I'm looking to create an Observable that will produce a new feed each time the value of this.pending changes. For example, if I update this.pending to be false i ...

Update the second select form's list after choosing an option in the first select form in Angular 4

In my form, I have incorporated two select elements within one form tag. The options in the second select element are dependent on the selection made in the first one. Currently, I have set up this functionality using a template-driven approach, with a (c ...

Description of how to define rows and columns for a Quasar QTable using TypeScript

Just curious if there is a Typescript definition available for the rows and columns of Qtable? Appreciate any help on this. Cheers, marnold ...

Trying to assign a value to a key on an object that is supposed to be unchangeable and has been locked in place. [ Angular2 + React Native ]

Currently, I am developing a mobile app using Angular2 + React Native. I encountered an issue when trying to run the following code: <Text [styleSheet]="styles.button" opacityFeedback (tap)="showMore=!showMore" testID="Show_More"> {{showMore ? & ...

Which specific part is the perfect choice?

I am currently in the process of developing a small app that connects to an API through Node.js and stores all posts in MongoDB. While I have completed this part successfully, I am now faced with the challenge of creating the front-end interface. The use ...

Slider components in Angular 4/6 Material, allowing for time scale customization spanning across 24 hours

Currently, I am utilizing Angular Material to craft a slider specifically designed for a 24-hour range. My objective is to have the value of the slider displayed on the side. So far, the following functionalities are up and running: I can capture t ...

Using Angular Ngrx to Retrieve and Showcase a Selection of Choices from a Java API

When accessing the Java API at localhost://company/products/123/fetchOptions, you can expect a response similar to the following: { "Increase": true, "Decrease" : true, "Like" : true, "Dislike" : true, "Old" : false, "Others" : true } Using Angula ...

`Database Schema Enforcement in Firestore: Custom Objects vs Security Rules`

Firestore, being a noSQL database, is schemaless. However, I want to ensure that the correct data type is being passed in. Custom Objects As per Firebase documentation, https://firebase.google.com/docs/firestore/manage-data/add-data class City { const ...

Having difficulty accessing certain code in TypeScript TS

Struggling with a TypeScript if else code that is causing errors when trying to access it. The specific error message being displayed is: "Cannot read properties of undefined (reading 'setNewsProvider')" Code Snippet if (this.newsShow != ...

Having trouble getting @types/express-session to function properly. Any suggestions on how to fix it?

My web-app backend is built with TypeScript and I've integrated express-session. Despite having @types/express and @types/express-session, I continue to encounter type errors that say: Property 'session' does not exist on type 'Request ...

The method JSON.stringify is not properly converting the entire object to a string

JSON.stringify(this.workout) is not properly stringifying the entire object. The workout variable is an instance of the Workout class, defined as follows: export class Workout { id: string; name: string; exercises: Exercise[]; routine: Ro ...

Working with intricately structured objects using TypeScript

Trying to utilize VS Code for assistance when typing an object with predefined types. An example of a dish object could be: { "id": "dish01", "title": "SALMON CRUNCH", "price": 120, ...

Organize and display a list of contacts alphabetically by the first letter of their

I have a list of contacts that I need help with. Despite searching on Stack Overflow, I couldn't find the answer. Can someone please assist? Thank you. export const rows = [ { id: 1, name: 'Snow', email: 'Jon', co ...

expand the module's children routes by including additional options from another module

Imagine we have a module called "Parent" which has some child routes: const routes: Routes = [ { path: '', component: ParentComponent, children: [ { path: '/:id', ...