2015-09-20 34 views
2

我怎樣才能重複調用一個javascript函數(repeatedFunction()),但是讓它成爲我們說的alert("This function is being executed for the first time")僅在repeatedFunction()第一次被激活,但是//other code總是被激活?另外,如何讓alert()允許再次激活一次,就像repeatedFunction()再次被執行一樣?如何使功能的一部分只執行一次,直到它被允許執行,否則

+0

重播功能,您可以隨時擁有'的setInterval(myFunction的,毫秒);' –

回答

3

功能是對象。您可以設置(以後清除)標記的功能,如果你喜歡:

function repeatedFunction() { 
    if (!repeatedFunction.suppress) { 
     alert("This function is being executed for the first time"); 
     repeatedFunction.suppress = true; 
    } 
    // ...other code here... 
} 

當你想重置,以獲得repeatedFunction任何代碼都可以清除repeatedFunction.suppress標誌:

repeatedFunction.suppress = false; 

該標誌沒有要上的功能,當然,你可以使用一個單獨的變量。


也就是說,我建議看大圖和檢查有問題的警報是否真的應該是函數的一部分都沒有。

+0

您的解決方案似乎是最適合我的問題的解決方案!謝謝。 –

6

您可以設置一個標誌。比方說,你有這樣的下面的代碼:

var flagAlertExecd = false; 
function repeatThis() { 
    if (!flagAlertExecd) { 
    alert("Only once..."); 
    flagAlertExecd = true; 
    } 
    // Repeating code. 
} 

而且重複這個代碼,它是很好的使用setInterval

setInterval(repeatThis, 1000); 
+0

什麼爲downvote原因,好嗎? –

0

你可以通過聲明一個變量並在你的函數中增加它來做到這一點。使用if語句,您可以檢查它被觸發了多少次。代碼:

var count = 0; 

function myfunc(){ 
if(count==0){ 
    alert("Triggering for the first time"); 
    count++; 
} 
    //Your always triggering code here 
} 

Demo

這甚至跟蹤了多少次的功能被觸發的記錄。如果您不想在nth時間內執行alert(),它會很有用。

您也可以使用布爾值。就像這樣:

var firstTime = true; 

function myfunc(){ 
if(firstTime){ 
    alert("Triggering for the first time"); 
    firstTime = false; 
} 
    //Your always triggering code here 
} 

Demo

第二種方法不會跟蹤了多少次的功能已被觸發的記錄,它只是確定是否該函數被調用的第一次或沒有。

這兩種方法都能正常工作。

0
var firstTime = true; 

var myFunction = function() { 
    if(firstTime) { 
    alert("This function is being executed for the first time"); 
    firstTime=false; 
    }else{ 
    //whatever you want to do... 
    } 
}; //firstTime will be true for the first time, after then it will be false 
var milliseconds = 1000; 
setInterval(myFunction, milliseconds); 
//the setInterval means that myFunction is repeated every 1000 milliseconds, ie 1 second. 
+0

這將不會執行始終執行的代碼,這是第一次。再看看這個問題! – Arjun

+0

@Arjun我修復了這個錯誤 –

2

的JavaScript closure approach將適合這個任務。它沒有全局變量,並將您的任務保存在一個函數中。

var closureFunc = function(){ 
    var numberOfCalls = 0; 
    return function(){ 
     if(numberOfCalls===0) 
     { 
      console.log('first run'); 
     } 
     numberOfCalls++; 

     console.log(numberOfCalls); 
    }; 
}; 

var a = closureFunc(); //0 
a(); //1 
a(); //2 
var a = closureFunc(); //drop numberOfCalls to 0 
a(); //1 

http://jsfiddle.net/hmkuchhn/