Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SetTimeout not delaying a function call [duplicate]

Can somebody please tell me why the setTimeout used in the code below isn't working? It just runs the function straightaway.

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

Any help appreciated.

like image 516
Mark_54 Avatar asked Feb 07 '12 22:02

Mark_54


People also ask

Does setTimeout repeat?

setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.

Is setTimeout a blocking call?

Explanation: setTimeout() is non-blocking which means it will run when the statements outside of it have executed and then after one second it will execute. All other statements that are not part of setTimeout() are blocking which means no other statement will execute before the current statement finishes.

Does setTimeout execute immediately?

Next, you can pass the milliseconds parameter, which will be the amount of time JavaScript will wait before executing the code. If you omit the second parameter, then setTimeout() will immediately execute the passed function without waiting at all.

How do I add a delay to a function call?

To delay a function call, use setTimeout() function. functionname − The function name for the function to be executed. milliseconds − The number of milliseconds. arg1, arg2, arg3 − These are the arguments passed to the function.


1 Answers

The problem is this line

setTimeout(adjust_for_font(id),2000);

This doesn't schedule the invoking of adjust_for_font(id) but instead invokes the function directly and schedules the return value. To schedule the invocation of the function wrap the call in a lambda

setTimeout(function() { adjust_for_font(id); },2000);
like image 197
JaredPar Avatar answered Oct 19 '22 06:10

JaredPar