我正在尝试编写一个JavaScript函数,当调用它时,执行DoSomething()函数一次,但可以重复触发以执行该函数,直到停止。
我正在使用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>