-1

I'm new to Vue.js. How do I use the setTimeout in Vue.js?

Here is where I want to timeout

dataReq.end((err, resp) => {
            resp = JSON.parse(resp.text)
            if (resp.status) {
              setTimeout(this.$router.push, 10000)(this.breadcrumbs[2].path)
            }
          })
osoda
  • 41
  • 2
  • 6
  • Does this answer your question? [setTimeout() not working called from vueJS method](https://stackoverflow.com/questions/45301063/settimeout-not-working-called-from-vuejs-method) – Darren Houston Feb 16 '20 at 22:53

2 Answers2

0

You shold b doing it like this:

dataReq.end((err, resp) => {
        resp = JSON.parse(resp.text)
        if (resp.status) {
          setTimeout(() => {
              this.$router.push(this.breadcrumbs[2].path);
          }, 10000)
        }
      })

setTimeout takes a function to be executed after timeout as 1st argument and $router.push() takes the path as an argument ,, guessing this.breadcrumbs[2].path is a valid path

Vamsi Krishna
  • 30,568
  • 8
  • 70
  • 78
  • @user2486 that's the reason i am using an arrow function. So that `this` is lexically scoped – Vamsi Krishna Nov 03 '17 at 09:20
  • @WaldemarIce you are wrong arrow functions bind the context of `this` lexically so it will work please have a look at this fiddle; http://jsfiddle.net/3ujdud6c/1/ – Vamsi Krishna Nov 03 '17 at 09:44
  • And what context have enclosing enviroment of setTimeout? You dont know. As setTimeout itself is called in arrow function... Whole example is wrong... –  Nov 03 '17 at 10:01
  • @WaldemarIce we know the enclosing environment as you said for `setTimeout` is the success call back of get request which is further enclosed in mounted where the value of `this` is the vue instance – Vamsi Krishna Nov 03 '17 at 10:04
  • Can you bet on it? I dont see context of whole end method. I dont know where and how is used. –  Nov 03 '17 at 10:08
  • 1
    @WaldemarIce yup i can bet on it ,,,, thats the reason i provided a link to a working fiddle – Vamsi Krishna Nov 03 '17 at 10:09
  • But your example have nothing to do with osoda code. You dont know where and how is using end method. –  Nov 03 '17 at 10:14
0

May be you have issue with referencing this,Try like this.

dataReq.end((err, resp) => {
    resp = JSON.parse(resp.text);
    if (resp.status) {
        var vm = this;
        setTimeout(function() {
            console.log("Do somthing here");
            // this is now referencing to setTimeout function, so use vm referenced above
            console.log(vm.breadcrumbs[2].path);
        }, 100);
    }
});
Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109