Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does setTimeout(myFunction, 0) work, but running the function itself not work?

This code should select the contents of a textarea when that textarea is selected. However, it doesn't work by itself:

        $("#form").focus(function() {
            $("#form").select();
        });

It only works when I give it a setTimeout of 0, like so:

        $("#form").focus(function() {
            setTimeout(function() {
                $("#form").select();
            }, 0);
        });

Why is that?

like image 283
bevanb Avatar asked Mar 17 '26 00:03

bevanb


1 Answers

It looks like the first code snippet is selecting, then deselecting the text. I suspect that the text selection is being handled behind the scenes after the focus event is finished, and setTimeout executes the select after the event (when the behind-the-scenes stuff has already happened).

like image 182
CheeseWarlock Avatar answered Mar 18 '26 13:03

CheeseWarlock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!