我想写一个JavaScript函数,当被调用时执行函数DoSomething()一次, 但可以触发执行该功能,直到触发停止。JavaScript的递归函数&setTimeout
我正在使用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>