如何使用参数调用函数作为setTimeout回调?

时间:2014-09-19 15:45:59

标签: javascript jquery

如何通过JQuery' s setTimeout调用带参数的函数?

这"工作",但该功能立即被调用:

var successFunc = function(data, textStatus_ignored, jqXHR_ignored)  {
    alert("sf data='" + data + "', textStatus_ignored='" + textStatus_ignored + "', jqXHR_ignored='" + jqXHR_ignored + "', color_id='" + color_id + "'");
    $('#toggle_color_like_cell_' + color_id).html(data);
};
var successFuncWithTimeout = function(data, textStatus_ignored, jqXHR_ignored)  {
    //alert("sfwt data='" + data + "', textStatus_ignored='" + textStatus_ignored + "', jqXHR_ignored='" + jqXHR_ignored + "', color_id='" + color_id + "'");

    setTimeout(successFunc(data, textStatus_ignored, jqXHR_ignored), 2000);
}

等待两秒钟,但根据警报,所有参数均为undefined

var successFuncWithTimeout = function(data, textStatus_ignored, jqXHR_ignored)  {
    //alert("sfwt data='" + data + "', textStatus_ignored='" + textStatus_ignored + "', jqXHR_ignored='" + jqXHR_ignored + "', color_id='" + color_id + "'");

    setTimeout(function(data, textStatus_ignored, jqXHR_ignored)  {
        alert("sf data='" + data + "', textStatus_ignored='" + textStatus_ignored + "', jqXHR_ignored='" + jqXHR_ignored + "', color_id='" + color_id + "'");
        $('#toggle_color_like_cell_' + color_id).html(data);
    }, 2000);
}

1 个答案:

答案 0 :(得分:1)

参数不需要传递到匿名函数,因为它们已经在范围内。 (感谢Stack Overflow上的this answer。)

var successFunc = function(data, textStatus_ignored, jqXHR_ignored)  {
    alert("sf data='" + data + "', textStatus_ignored='" + textStatus_ignored + "', jqXHR_ignored='" + jqXHR_ignored + "', color_id='" + color_id + "'");
    $('#toggle_color_like_cell_' + color_id).html(data);
};
var successFuncWithTimeout = function(data, textStatus_ignored, jqXHR_ignored)  {
    //alert("sfwt data='" + data + "', textStatus_ignored='" + textStatus_ignored + "', jqXHR_ignored='" + jqXHR_ignored + "', color_id='" + color_id + "'");

    setTimeout(function()  {
        successFunc(data, textStatus_ignored, jqXHR_ignored);
    }, 2000);
}

使用相同的概念,这也有效:

var successFuncWithTimeout = function(data, textStatus_ignored, jqXHR_ignored)  {
    //alert("sfwt data='" + data + "', textStatus_ignored='" + textStatus_ignored + "', jqXHR_ignored='" + jqXHR_ignored + "', color_id='" + color_id + "'");

    setTimeout(function()  {
        alert("sf data='" + data + "', textStatus_ignored='" + textStatus_ignored + "', jqXHR_ignored='" + jqXHR_ignored + "', color_id='" + color_id + "'");
        $('#toggle_color_like_cell_' + color_id).html(data);
    }, 2000);
}