当前位置: 首页 > article >正文

js实现异步和延时

说明:最近碰到几个需求,
1.使用js实现延时几秒,执行代码的操作 setTimeout
2.使用js实现子线程执行耗时操作,主线程不需要等待子线程任务执行完成,子线程的任务执行完成后,把执行结果回调给主线程,更新ui和界面
效果图:
step1:

import {Component, OnInit} from '@angular/core';


/*参考网址: https://zhuanlan.zhihu.com/p/172378607*/

@Component({
  selector: 'app-user',
  standalone: true,
  imports: [],
  templateUrl: './user.component.html',
  styleUrl: './user.component.css'
})
export class UserComponent implements OnInit {


  constructor() {
    console.log('constructor')
  }

  ngOnInit(): void {
    console.log('ngOnInit')
    this.test();
  }

  private getSomething() {
    return "something";
  }

  async testAsync() {
    return Promise.resolve("hello async");
  }

  async test() {
    const v1 = await this.getSomething();
    const v2 = await this.testAsync();
    console.log(v1, v2);
  }

}

step2:

import {Component, OnInit} from '@angular/core';

@Component({
  selector: 'app-user',
  standalone: true,
  imports: [],
  templateUrl: './user.component.html',
  styleUrl: './user.component.css'
})
export class UserComponent implements OnInit{


  constructor() {
    console.log('constructor')
  }

  ngOnInit(): void {
    console.log('ngOnInit')


    console.log('Hello');
    setTimeout(() => { console.log('World!'); }, 2000);

    console.log('Hello');
    setTimeout(() => { console.log('World!'); }, 2000);
    console.log('Goodbye!');

  }

}

step3:

import {Component, OnInit} from '@angular/core';

@Component({
  selector: 'app-user',
  standalone: true,
  imports: [],
  templateUrl: './user.component.html',
  styleUrl: './user.component.css'
})
export class UserComponent implements OnInit {


  constructor() {
    console.log('constructor')
  }

  ngOnInit(): void {
    console.log('ngOnInit')

    this.takeLongTime().then(v => {
      console.log("got", v);
    });

  }

  takeLongTime() {
    return new Promise(resolve => {
      setTimeout(() => resolve("long_time_value"), 2000);
    });
  }
}

step4:

import {Component, OnInit} from '@angular/core';

@Component({
  selector: 'app-user',
  standalone: true,
  imports: [],
  templateUrl: './user.component.html',
  styleUrl: './user.component.css'
})
export class UserComponent implements OnInit {


  constructor() {
    console.log('constructors')
  }

  ngOnInit(): void {
    console.log('ngOnInit')
    this.test();
  }

  takeLongTime() {
    return new Promise(resolve => {
      setTimeout(() => resolve("long_time_values"), 1000);
    });
  }

  async test() {
    const v = await this.takeLongTime();
    console.log(v);
  }
}

step5:

import {Component, OnInit} from '@angular/core';

@Component({
  selector: 'app-user',
  standalone: true,
  imports: [],
  templateUrl: './user.component.html',
  styleUrl: './user.component.css'
})
export class UserComponent implements OnInit {


  constructor() {
    console.log('constructors')
  }

  ngOnInit(): void {
    console.log('ngOnInit')
    this.doIt();
  }

  takeLongTime(n: any) {
    return new Promise(resolve => {
      setTimeout(() => resolve(n + 2000), n);
    });
  }

  step1(n: any) {
    console.log(`step1 with ${n}`);
    return this.takeLongTime(n);
  }

  step2(n: any) {
    console.log(`step2 with ${n}`);
    return this.takeLongTime(n);
  }

  step3(n: any) {
    console.log(`step3 with ${n}`);
    return this.takeLongTime(n);
  }

  doIts() {
    console.time("doIt");
    const time1 = 300;
    this.step1(time1)
      .then(time2 => this.step2(time2))
      .then(time3 => this.step3(time3))
      .then(result => {
        console.log(`result is ${result}`);
        console.timeEnd("doIt");
      });
  }

  async doIt() {
    console.time("doIt");
    const time1 = 300;
    const time2 = await this.step1(time1);
    const time3 = await this.step2(time2);
    const result = await this.step3(time3);
    console.log(`result is ${result}`);
    console.timeEnd("doIt");
  }

}


step6:

import {Component, OnInit} from '@angular/core';

@Component({
  selector: 'app-user',
  standalone: true,
  imports: [],
  templateUrl: './user.component.html',
  styleUrl: './user.component.css'
})
export class UserComponent implements OnInit {


  constructor() {
    console.log('constructors')
  }

  ngOnInit(): void {
    console.log('ngOnInit')
    this.doIt()
  }

  step1(n: any) {
    console.log(`step1 with ${n}`);
    return this.takeLongTime(n);
  }

  step2(m: any, n: any) {
    console.log(`step2 with ${m} and ${n}`);
    return this.takeLongTime(m + n);
  }

  step3(k: any, m: any, n: any) {
    console.log(`step3 with ${k}, ${m} and ${n}`);
    return this.takeLongTime(k + m + n);
  }

  takeLongTime(n: any) {
    return new Promise(resolve => {
      setTimeout(() => resolve(n + 2000), n);
    });
  }

  async doIt() {
    console.time("doIt");
    const time1 = 300;
    const time2 = await this.step1(time1);
    const time3 = await this.step2(time1, time2);
    const result = await this.step3(time1, time2, time3);
    console.log(`result is ${result}`);
    console.timeEnd("doIt");
  }


}

end


http://www.kler.cn/a/373543.html

相关文章:

  • 【测试工具】通过Jmeter压测存储过程
  • 【问题解决】pnpm : 无法将“pnpm”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。
  • Spring自动装配(特别版)
  • Chrome浏览器音/视频无法自动播放
  • 利用摄像机实时接入分析平台LiteAIServer视频智能分析软件进行视频监控:过亮过暗检测算法详解
  • Pinctrl子系统pinctrl_desc结构体进一步介绍
  • 隨便 20241028 ISR 和 OSR 在 Kafka 中的详细解析
  • Nginx部署前端需要了解的知识
  • EfficientNet-B6模型实现ISIC皮肤镜图像数据集分类
  • 整合SSM框架(2)
  • 雷赛DMC5X10系列脉冲运动控制卡——机械原点和工作原点原理
  • BGP 及 4+ 的一些特性及配置笔记
  • 外包干了7天,技术明显退步。。。。。
  • Go:package
  • 传奇架设教程,M2报错无法找到城堡信息文件的解决方法
  • 【c++篇】:模拟实现string类--探索字符串操作的底层逻辑
  • oracle获取中文拼音/WB
  • isp框架代码理解
  • python debug作业
  • 前端vue2迁移至uni-app
  • 产品宣传册制作成电子产品宣传册用什么软件?
  • ollama 在 Linux 环境的安装
  • Leetcode 79 Word search
  • 保障农民工工资!我们这么做:
  • 前端面试题-token的登录流程、JWT
  • Django+Vue智慧分析居家养老系统统的设计与实现