G
G
grigorie19902020-04-18 14:03:44
JavaScript
grigorie1990, 2020-04-18 14:03:44

How to delay execution in an asynchronous function that is called every second?

Good afternoon!
How to delay execution in an asynchronous function. When I add clearTimeout(timerId); the function does not work, without it the delay works only the first time. How to make sure that there is a delay every time?

const {setIntervalAsync} = require('set-interval-async/dynamic');
  ...
  mounted(){
  ...
      this.interval();
        },
        methods: {
            interval: function () {
                setIntervalAsync(
                    async () => {
                        await this.changeAlert();
                    },
                    1000
                );
            },
            changeAlert: async function () {
                console.log(789);
                let timerId = setTimeout(() => {
                    if (this.alertArr.length > 0) {
                        this.alertCurrent = this.alertArr[0];
                        console.log(this.alertCurrent);
                    } else {
                        this.alertCurrent = null;
                    }
                    this.alertArr.splice(0, 1);
                }, 5000);
                 clearTimeout(timerId);
            },
        }
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Somewhere Intech, 2020-04-18
@john36allTa

in changeAlert you start a timer in which you describe the callback, and then immediately reset the timer and the callback does not work. In other words, you gave the machine a bunch of instructions and immediately canceled them.
It's not clear what you want to achieve, maybe this will give you the right idea;)

changeAlert: function() {
    console.log(789);
    return new Promise((resolve, reject)=>{
        let timerId = setTimeout(() => {
            if (this.alertArr.length > 0) {
                this.alertCurrent = this.alertArr[0];
                console.log(this.alertCurrent);
            } else {
                this.alertCurrent = null;
            }
            this.alertArr.splice(0, 1);
            resolve()
            if (false) reject("error description");
        }, 5000);
    })
}

A
Anton Alexandrov, 2020-04-22
@Toscha

Perhaps this will help:

data: () => ({
 interval: 0,
 counter: 0
}),
mounted () {
 this.start()
},
methods: {
 start () {
  this.counter = 0
  clearInterval(this.interval)
  this.interval = setInterval( () => {
    this.counter++
    console.log(this.counter)
  }, 1000)
 },
 stop () {
  this.counter = 0
  clearInterval(this.interval)
 }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question