如何在 Javascript 中重置 setTimeout() 的时间值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7186587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:14:06  来源:igfitidea点击:

How to reset the time value of setTimeout() in Javascript?

javascripttimersettimeout

提问by Vin

I want to display an alert() box, just 10 seconds after user stops writting in a textbox.

我想在用户停止在文本框中写入后 10 秒显示一个 alert() 框。

I used following javascript code to open alertbox -

我使用以下 javascript 代码打开警报框 -

function txtkeyup(e){
  setTimeout(function () {
    alert('submit?');
  }, 10000);
  return true;
}

and the HTML code is -

并且 HTML 代码是 -

<input type='textbox' name='searchquery' value='' onkeyup='return txtkeyup();'>

Now the browser is giving alertbox, 10 seconds after every onkeyup event in the inputbox. To make only one request, i have to reset the setTimeout() timer on every keyup event so the alertbox will be display if user doesnt press a button for 10 seconds.

现在浏览器会在输入框中的每个 onkeyup 事件后 10 秒发出警报框。为了只发出一个请求,我必须在每个按键事件上重置 setTimeout() 计时器,以便在用户 10 秒内未按下按钮时显示警报框。

How can reset the timer of previously called 'setTimeout()' in javascript? Please guide me..

如何在 javascript 中重置以前称为“setTimeout()”的计时器?请指导我..

回答by Thomas

var myTimeout = setTimeout ( ...)

var myTimeout = setTimeout ( ...)

to clear it simply write clearTimeout(myTimeout);

清除它只需写 clearTimeout(myTimeout);