[英]Javascript: Call a function again after specific time period
如果我想首先立即运行功能(onclick),但是稍后我希望在每次onclick运行之前将超时设置为3秒,该怎么办? 有任何想法吗?
function FetchData() {
}
编辑:@epascarello代码确实做了我想要它做的事情。
顺便说一句,当单击按钮时,有什么方法可以删除“旧”消息,但不能删除所有div内容-仅删除此onclick函数添加的内容(旧内容,因此只会出现最新消息)?
您可以使用类似h
的处理程序:
function h(){
//
// do Your code
//
h.to = h.to ?
clearTimeout(h.to)
:
setTimeout(h, 3000);
}
您可以有一个标志来检查它是否是第一次单击。 积分@epascarello
var timeout = null; var firstClick = false; function notify() { console.log("Hello World!"); } function clickHandler() { if(!firstClick){ firstClick = true; notify(); return true; } if (timeout) { resetTimeout(); } initTimeout(); } function initTimeout() { timeout = setTimeout(notify, 3000); } function resetTimeout() { window.clearTimeout(timeout); timeout = null }
<button onclick="clickHandler()">Click me!!!</button>
因此,监听第一次单击并调用函数,然后翻转一个布尔值并设置延迟。
(function(){ var _first = true, timer; function FetchData() { var delay = _first ? 0 : 3000; if (timer) window.clearTimeout(timer); timer = window.setTimeout(_runFetch, delay); _first = false; } /* Or you can do if a few microseconds matter function FetchData() { if (_first) { _runFetch() _first = false; } else { if (timer) window.clearTimeout(timer); timer = window.setTimeout(_runFetch, 3000); } } */ function _runFetch() { var out = document.getElementById("out"); out.innerHTML = (new Date()) + "<br/>" + out.innerHTML; } document.getElementById("btn").addEventListener("click", FetchData); }());
<button id="btn">Click</button> <div id="out"></div>
尝试这个:
var first = true;
function FetchData() {
if(first) {
//magic
first = false;
} else {
window.setTimeout(function() {
//magic
}, 3000);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.