最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to delay a method call after 1 min in angular or rxjs using Delay operator - Stack Overflow

programmeradmin7浏览0评论

HI here my scenario is i need call a method only after 1 min here i can also set time out but instead is it possible using delay method like below

getMethod(){
 
}


delay(1000,this.getMethod())

or any other better approach

HI here my scenario is i need call a method only after 1 min here i can also set time out but instead is it possible using delay method like below

getMethod(){
 
}


delay(1000,this.getMethod())

or any other better approach

Share Improve this question edited Sep 8, 2020 at 5:39 Madpop asked Sep 8, 2020 at 5:32 MadpopMadpop 7254 gold badges29 silver badges63 bronze badges 9
  • Check delay or debounce time operator in RxJs – Narkhede Tushar Commented Sep 8, 2020 at 5:37
  • stackoverflow./questions/14226803/… possible duplicate – user12504785 Commented Sep 8, 2020 at 5:38
  • Does this answer your question? Wait 5 seconds before executing next line – user12504785 Commented Sep 8, 2020 at 5:38
  • @Frost these are promises i am trying to achieve it using delay and using delay also i want to call a method – Madpop Commented Sep 8, 2020 at 5:40
  • @NarkhedeTushar how can we add a method in delay operator ? – Madpop Commented Sep 8, 2020 at 5:41
 |  Show 4 more ments

3 Answers 3

Reset to default 4

If you are using rxjs and Angular then you probably want to use the RxJs timer subject

import { timer } from 'rxjs';
const minute = 1000 * 60;

function helloWorld() {
  console.log('hello');
}

timer(minute).subscribe(helloWorld);

If you are looking into what RxJs Subject or Operator you want, try checking the RxJs Operator Decision Tree for help.

you can use rxjs delay pipe:

getMethod(): Observable {
  return of(2)
}
const delayedMethod = getMethod.pipe(delay(1000))
delayedClicks.subscribe(x => console.log(x));

You can use a promise & async-await to achieve this. Check below code

  const sleep = (milliseconds) => {
    return new Promise(resolve => setTimeout(resolve, milliseconds))
}

await sleep(2000) // This will give 2 seconds delay
发布评论

评论列表(0)

  1. 暂无评论