SetTimeout不延迟函数调用

时间:2012-02-07 22:05:11

标签: 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();
}

任何帮助表示感谢。

7 个答案:

答案 0 :(得分:36)

问题在于这一行

setTimeout(adjust_for_font(id),2000);

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

setTimeout(function() { adjust_for_font(id); },2000);

答案 1 :(得分:5)

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

setTimeout旨在运行如下:

setTimeout('adjust_for_font',2000);

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

setTimeout(function(){adjust_for_font(id);}, 2000);

答案 2 :(得分:3)

更改

setTimeout(adjust_for_font(id),2000);

setTimeout("adjust_for_font(id)",2000);

答案 3 :(得分:3)

这应该可以解决问题:

setTimeout(adjust_for_font, 2000, id);

我传递的函数名称是在2000毫秒过后执行的。在您的代码中,您传递的是adjust_for_font的结果。函数名后面的括号会在解析(立即)后立即执行。

答案 4 :(得分:2)

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

setTimeout(function() {
    adjust_for_font(id);
},2000);

答案 5 :(得分:1)

SetTimeout语法是setTimeout(function,milliseconds,param1,param2,...)

此处“功能”不是指调用该功能。它应该是真正的功能。

因此您必须将代码更改为

的setTimeout(adjust_for_font,2000,ID); (注意:参数id应在毫秒参数后传递)

或者您可以将第一个参数设置为低于标准

setTimeout(function(){adjust_for_font(id);},2000);

答案 6 :(得分:0)

这是我的经历。只是指定setTimeout()将导致它在页面加载时执行,即使它的父函数未被调用。使它变成像这样的变量..

<强>前

function xyz(){
  //do something if needed
  setTimeout(function abc, duration);
  //setTimeout will be executed even before xyz() call
}

<强>后

function xyz(){
  //do something if needed
  var t=setTimeout(function abc, duration);
  //this time, setTimeout will be executed upon xyz() call and not upon pageload
}
相关问题