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

javascript - setTimeout function not working with value change - Stack Overflow

programmeradmin0浏览0评论

setTimeout function is not working as per the expectations. Here's my code:

$(document).delegate('.pur','click', function(e){
    var productid = $(this).attr('id');
    var quantity = $('#qua').val();
    if(quantity>0){
        this.value='Adding';
    }
    else{
        this.value='Min 100';
        setTimeout(function(){this.value='Buy now'}, 3000);
    }
});

Above code doesn't work at all, it doesn't change the value after 3 seconds as it's expected to do. Any flaw or something in it? Can anyone help finding what's wrong with it?

setTimeout function is not working as per the expectations. Here's my code:

$(document).delegate('.pur','click', function(e){
    var productid = $(this).attr('id');
    var quantity = $('#qua').val();
    if(quantity>0){
        this.value='Adding';
    }
    else{
        this.value='Min 100';
        setTimeout(function(){this.value='Buy now'}, 3000);
    }
});

Above code doesn't work at all, it doesn't change the value after 3 seconds as it's expected to do. Any flaw or something in it? Can anyone help finding what's wrong with it?

Share Improve this question edited Jun 19, 2014 at 18:40 j08691 208k32 gold badges269 silver badges280 bronze badges asked Jun 19, 2014 at 18:32 Guy in the chairGuy in the chair 1,0651 gold badge14 silver badges45 bronze badges 3
  • 2 see here, same issue. The problem is the scope of this, you should create a reference to it outside of the setTimeout – Austin Greco Commented Jun 19, 2014 at 18:35
  • 2 The problem is that the value of this in the function you pass to setTimeout() won't be what you want it to be. – Pointy Commented Jun 19, 2014 at 18:35
  • Yes, got it, problem solved, please make it your answer :) – Guy in the chair Commented Jun 19, 2014 at 18:37
Add a ment  | 

3 Answers 3

Reset to default 5

Scoping issue

inside your setTimeout, "this" doesn't refer to the same object as outside setTimeout.

Fix it like this

$(document).delegate('.pur','click', function(e){
    var productid = $(this).attr('id');
    var quantity = $('#qua').val();
    if(quantity>0){
        this.value='Adding';
    }
   else{
       this.value='Min 100';
       var that = this; // hold a reference to "this" as "that" 
       setTimeout(function(){that.value='Buy now'}, 3000); // use "that" instead of   "this"
    }
});

The reference to "this" in the anonymous function does not point to anything. You could change it like this (i.e., self being a variable in the visibility scope of your anonymous function):

     this.value='Min 100'; 
     var self = this;
     setTimeout(function(){self.value='Buy now'}, 3000);

This should also do the trick

setTimeout(function() { this.value = 'Buy now'; }.bind(this), 3000)
发布评论

评论列表(0)

  1. 暂无评论