Answer the question
In order to leave comments, you need to log in
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
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);
})
}
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 questionAsk a Question
731 491 924 answers to any question