setTimeout does not wait for specified number of milliseconds
I would like to have a form triggering submit after a few seconds of inactivity (using the onKeyup
event).
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">
开发者_StackOverflow<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... the forms gets submitted at every onKeyUp
event it seems. It does not wait for the timer to reach the specified 10,000 milliseconds.
Is there a way to fix this?
The first parameter to setTimeout()
needs to be a function object (or a string, but you should not use that). Like this:
timer = setTimeout(function () {
$("#getJSONForm").submit();
}, 10000);
You are currently passing the value of $("#getJSONForm").submit()
to setTimeout()
, which is probably not what you want.
Besides that, i would recommend using jQuery's event handling instead of HTML arguments. It is way more elegant, flexible and easier to maintain. You can do it like this:
$('#getJSONForm textarea').keyup(function () {
// the content of your onKeyUp() function goes here
});
Have a look at the API documentation on this topic.
精彩评论