重新加载函数Javascript的最佳做法

时间:2015-12-30 17:05:37

标签: javascript jquery

我已经纠正了代码并且它有效,这样做是好的做法吗?

$(document).on("click", ".upvotes", function datos(){

    $.post('/post/', function(data){

            console.log(data);
            $('.vote_count').html(data.number);
            setTimeout(function(data){ 
                /* Do stuff with data variable in here */ 
                console.log(data);
                datos();
                //$('.vote_count').html();
            }, 1000);
    });
});

1 个答案:

答案 0 :(得分:0)

您的代码需要像这样重写:

var timer;

$(document).on("click", ".upvotes", function(){

    $.post('/post/', function(data){

            console.log(data);
            $('.vote_count').html(data.number);
            timer = setTimeout(function(data){ 
                /* Do stuff with data variable in here */ 
            }, 1000);

    });

});

$(".another-button").on("click", function(){

    // This will stop the setTimeout that was initialized in the button click above
    clearTimeout(timer);

});