SetTimeout不延迟函数调用

Mar*_*_54 14 javascript settimeout

有人可以告诉我为什么在下面的代码中使用的setTimeout不起作用?它只是直接运行功能.

function change_txt_font(elem, id, text_fnt){
    current_width = parseInt($('#span_text'+id).css('width')); 
    current_height = parseInt($('#span_text'+id).css('height')); 
    current_font_size = parseInt($("#span_text"+id).css("font-size"));

    parent.document.getElementById(elem+'_f').value=text_fnt;

    $('#span_text'+id).css('font-family',text_fnt);
    $('#'+elem).css('font-family',text_fnt); 
    setTimeout(adjust_for_font(id),2000);
    }

function adjust_for_font(id){
        alert("function")
        alert("id = "+id)
    new_height = parseInt($('#span_text'+id).css('height'));
    new_width = parseInt($('#span_text'+id).css('width'));
    width_ratio = parseFloat(current_width/new_width)
    height_ratio = parseFloat(current_height/new_height)
    new_font_size = current_font_size * Math.min(width_ratio,height_ratio)
    $("#text"+id).css("font-size", (parseFloat(new_font_size) - 1) + "px");
    $("#span_text"+id).css("font-size", (parseFloat(new_font_size) - 1) + "px");
    document.getElementById("form_front_text"+id).submit();
}document.getElementById("form_front_text"+id).submit();
}
Run Code Online (Sandbox Code Playgroud)

任何帮助赞赏.

Jar*_*Par 36

问题是这一行

setTimeout(adjust_for_font(id),2000);
Run Code Online (Sandbox Code Playgroud)

这不会调度调用,adjust_for_font(id)而是直接调用函数并调度返回值.安排函数的调用将调用包装在lambda中

setTimeout(function() { adjust_for_font(id); },2000);
Run Code Online (Sandbox Code Playgroud)


Fra*_*wis 5

通过不在函数周围添加引号,函数将立即处理,setTimeout将运行(但不会处理函数)并且您不知道究竟发生了什么.

setTimeout旨在运行如下:

setTimeout('adjust_for_font',2000);
Run Code Online (Sandbox Code Playgroud)

或者在回调中使用匿名函数是另一种选择:

setTimeout(function(){adjust_for_font(id);}, 2000);
Run Code Online (Sandbox Code Playgroud)


T. *_*one 3

按照您的编写方式,就好像 的输出adjust_for_font(id)是 的第一个参数的输入setTimeout。第一个参数应该是函数,而不是函数的结果。试试这个吧...

setTimeout(function() {
    adjust_for_font(id);
},2000);
Run Code Online (Sandbox Code Playgroud)