[Vuejs]-Continuation of the function after calling setInterval

0👍

In JS, all the statements are synchronous. By default, it doesn’t wait for functions like progress_bar(). Moreover, setInterval is also synchronous. It means that your progress_bar() function doesn’t wait for set Interval to complete to return. In order to do that, you need to make progress_bar() function return a promise.

progress_bar: function() {
    var vm = this   
    return new Promise(function(resolve,reject) {
        var width = 5
        $("#progess-modal").modal('show');
        vm.progress = 0;
        setInterval(function() {
            vm.progress += width;
            if (vm.progress >= 100) {
                $("#progess-modal").modal('hide');
                resolve();
            }
        }, 500)
    })
}

Then in the main code,

$("#progess-modal").modal('show');
vm.progress = 0;
var that = this;
this.progress_bar().then(function(res) {
    axios.post('http://task.ru.xsph.ru/task.php',
            'text=' + that.text
        )
        .then(res => {
            that.getUsers()
            that.closeNav()
        })
        .catch(error => {
            showModal: true
            that.getUsers()
        })
})

This makes sure that progress_bar() function only returns when you actually want to return i.e. inside setInterval(). the .then() is then run after you resolve the Promise

Leave a comment