javascript - 递归函数和 setTimeout
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7246441/
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
javascript - recursive function & setTimeout
提问by mustapha george
I am trying to write a javascript function that when called performs function DoSomething() once, but can be triggered to perform the function repeatedly until triggered to stop.
我正在尝试编写一个 javascript 函数,该函数在调用时执行一次函数 DoSomething(),但可以被触发以重复执行该函数,直到被触发停止。
I am using setTimeout() function. I am not sure if this is best method from performance and memory point of view. Also I would like to avoid global variable if possible
我正在使用 setTimeout() 函数。从性能和内存的角度来看,我不确定这是否是最佳方法。如果可能的话,我也想避免全局变量
<!DOCTYPE html>
<html>
<script src="jquery.js"></script>
<script>
var globalCheckInventory = false;
$(document).ready(function(){
// start checking inventory
globalCheckInventory = true;
myTimerFunction();
});
// check inventory at regular intervals, until condition is met in DoSomething
function myTimerFunction(){
DoSomething();
if (globalCheckInventory == true)
{
setTimeout(myTimerFunction, 5000);
}
}
// when condition is met stop checking inventory
function DoSomething() {
alert("got here 1 ");
var condition = 1;
var state = 2 ;
if (condition == state)
{
globalCheckInventory = false;
}
}
</script>
采纳答案by g.d.d.c
This is probably the easier way to do what you're describing:
这可能是执行您所描述的操作的更简单方法:
$(function () {
var myChecker = setInterval(function () {
if (breakCondition) {
clearInterval(myChecker);
} else {
doSomething();
}
}, 500);
});
回答by Alex Turpin
Another way to do it would be the store the timer ID and use setInterval
and clearInterval
另一种方法是存储计时器 ID 并使用setInterval
和clearInterval
var timer = setInterval(DoSomething);
function DoSomething() {
if (condition)
clearInterval(timer);
}
回答by sholsinger
I see nothing wrong with your implementation other than the pollution of the global namespace. You can use a closure (self-executing function) to limit the scope of your variables like this:
除了全局命名空间的污染之外,我认为您的实现没有任何问题。您可以使用闭包(自执行函数)来限制变量的范围,如下所示:
(function(){
var checkInventory = false, inventoryTimer;
function myTimerFunction() { /* ... */ }
function doSomething() { /* ... */ }
$(document).ready(function(){
checkInventory = true;
/* save handle to timer so you can cancel or reset the timer if necessary */
inventoryTimer = setTimeout(myTimerFunction, 5000);
});
})();
回答by Geoff Moller
Encapsulate it:
封装它:
function caller(delegate, persist){
delegate();
if(persist){
var timer = setInterval(delegate, 300);
return {
kill: function(){
clearInterval(timer);
}
}
}
}
var foo = function(){
console.log('foo');
}
var _caller = caller(foo, true);
//to stop: _caller.kill()