gpt4 book ai didi

javascript - setTimeout 不等待指定的毫秒数

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:37:51 26 4
gpt4 key购买 nike

我想要一个在几秒钟不活动后触发提交的表单(使用 onKeyup 事件)。

我的代码如下:

<!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>

但是...表单似乎在每个 onKeyUp 事件中提交。它不会等待计时器达到指定的 10,000 毫秒。有办法解决这个问题吗?

最佳答案

setTimeout() 的第一个参数必须是函数对象(或字符串,但您不应该使用它)。像这样:

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

您目前正在将 $("#getJSONForm").submit() 的值传递给 setTimeout(),这可能不是您想要的。

除此之外,我建议使用 jQuery 的事件处理而不是 HTML 参数。它更优雅、更灵活且更易于维护。你可以这样做:

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

看看the API documentation关于这个话题。

关于javascript - setTimeout 不等待指定的毫秒数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5105621/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com