2014-10-30 121 views
0

假設我有這個簡單的JavaScript函數:JavaScript - 如何創建一次只能運行一次的函數?

var exclusiveFunction = function(){ 
    for(index in firstArray) 
    { 
     for(secondIndex in firstArray[index]) 
     { 
      // do stuff to firstArray[index][secondIndex] 
     } 
    } 
} 

我的問題:有一個機會,這個代碼被多次調用前一個呼叫可以完成整個功能。我想什麼:

if(exclusiveFunction.workingAtTheMoment) 
{ 
     exclusiveFunction.stopFunction(); 
     exclusiveFunction(); 
} 

基本上,檢查功能正在運行,如果是,停止它(和它運行的每個實例),並再次啓動它。這可能嗎?

+3

JavaScript是單線程的。 – 2014-10-30 12:17:42

+0

如果函數正在運行,可以用標誌來解決,停止函數 - 不可能。 「一次運行一次」 - 非常不清楚 - 一次循環?每次一次? – Evgeniy 2014-10-30 13:01:22

回答

0

JavaScripts是單線程的,應該使用回調來提供異步行爲。你的函數沒有任何回調。因爲它的工作在你想要的方式..的

+0

回調不會產生任何併發。 – 2014-10-30 12:28:25

+0

據我所知,回調用於在單線程事件循環中創建時分複用。這會產生併發性...我錯在哪裏? – 2014-10-30 12:36:19

+0

回調只是一種傳遞行爲而不是價值的方式。它與時間或併發無關。您不能使用單個線程進行併發。 – 2014-10-30 15:19:06

0

您可以使用varible保持功能excetuion的軌道

var isFunRunning =0; 

var exclusiveFunction = function(){ 
if(isFunRunning==0) 
{  
    isFunRunning =1;  
    for(index in firstArray) 
     { 
      for(secondIndex in firstArray[index]) 
      { 
       // do stuff to firstArray[index][secondIndex] 
      } 
     } 
    isFunRunning=0; 
} 
else { 

//code to keep count of function triggered in between 

} 
     } 

,或者通過走這 http://api.jquery.com/jquery.callbacks/

OR __________________________________________________________________-

var callbacks = $.Callbacks(); 
var count =0; 

var exclusiveFunction = function(){ 

    if(isFunRunning==0) 
    {  
     isFunRunning =1;  
     for(index in firstArray) 
      { 
       for(secondIndex in firstArray[index]) 
       { 
        // do stuff to firstArray[index][secondIndex] 
       } 
      } 
     isFunRunning=0; 
    } 
    else { 

     callbacks.add(exclusiveFunction); 
     count ++; 

    } 
      } 

然後觸發回撥

0

我不確定是否有機會創建並行函數(可能是事件或異步;我對這個想法不感興趣),但是你可以停止這樣的功能:

window.someCounter = 0; 
function doSomethingUntilOtherCall(){ 
    var myID = ++window.someCounter; 
    while (myID === window.someCounter){ 
     // do something 
    } 
}