我想寫一個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>