SetTimeout does not wait for the specified number of milliseconds

I would like to have a function that runs the submit function after a few seconds of inactivity (using an event onKeyup).

My code is as follows:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Title</title>
    </head>
    <body>
        <form id="getJSONForm">
            <textarea rows="1" cols="10" onKeyUp="onKeyUp()"></textarea>
            <input type="submit" value="Submit" id="getJSON" />
        </form>

        <div id="result"  class="functions"></div>

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <script type="text/javascript">
            $.ajaxSetup ({
                cache: false
            });

            var timer;

            function onKeyUp() {
                stoper();
                timer = setTimeout ( $("#getJSONForm").submit(), 10000 ); 
            }

            function stoper() {
                clearTimeout(timer);
            }

            $("#getJSONForm").submit(function(){
                    $("#result").html("hello");
                    return false;
            });
        </script>
    </body>
</html>

But ... forms are obtained in every event onKeyup. It does not wait until the timer reaches the specified 10,000 milliseconds. Is there any way to fix this?

+3
source share
1 answer

The first parameter setTimeout()should be a function object (or a string, but you should not use this). Like this:

timer = setTimeout(function () {
   $("#getJSONForm").submit();
}, 10000);

You are currently passing the value $("#getJSONForm").submit()to setTimeout(), which is probably not what you want.

, jQuery HTML. , . :

$('#getJSONForm textarea').keyup(function () {
   // the content of your onKeyUp() function goes here
});

API .

+7

Source: https://habr.com/ru/post/1794447/


All Articles