2012-03-20 124 views
2

我有功能Start()準備就緒。當我點擊.ExampleClick時,我想停止運行功能Start()。這是我的例子...點擊返回False /停止jQuery功能

$(document).ready(function(){ 

    $(function Start(){ 
     // Do Stuff on Ready 
    }); 

    $(document).on("click",".ExampleClick",function() { 
    // When this is fired, function Start() should stop running 
    }); 

}); 

什麼是最好的方法來實現我想要做的?

+2

你不能做到這一點。至少不理智。 – 2012-03-20 17:49:45

+0

Start需要運行多久? @Daniel,這並非完全正確。 :) – 2012-03-20 17:50:13

+0

@ElliotBonneville - 當用戶加載文檔時完成。經常 – Joe 2012-03-20 17:51:31

回答

6

如果Start永遠循環,你的瀏覽器將掛起。 JavaScript函數不能真正並行運行。假設Start確實是一些意味着永久循環的後臺進程,那麼您需要重新思考並執行一次,然後安排自己再次執行某個點,以便處理其他事件。

每次Start執行時,它可以檢查上單擊處理保持一定的狀態來決定它是否應該運行,並再次排隊本身:

$(document).ready(function(){ 

    var clicked = false; 

    var Start = function() { 
     if (clicked) return; 

     // Do Stuff on Ready 

     setTimeout(Start, 100); 
    }; 

    Start(); 

    $(document).on("click",".ExampleClick",function() { 
    // When this is fired, function Start() should stop running 

    clicked = true; 
    }); 

}); 
+0

+1用於管理清楚我在想什麼。 =) – 2012-03-20 17:57:17

+0

謝謝@meagar。這很有幫助,雖然我確實有一個setTimeout來重新安排自己,但我沒有在這篇文章中提到它。 – Joe 2012-03-20 18:01:01

0

更新:正如其他人指出的,我以前的解決方案是完全錯誤的。我用的setInterval/clearInterval方法取代它(正確性的緣故 - 其他人已經指出,更好的/類似的解決方案):

$(document).ready(function(){ 

    var start = setInterval(
     function Start(){ 
      // Do Stuff on Ready 
     }, 
     someReasonableTimeFrame 
    ); 

    $(document).on("click",".ExampleClick",function() { 
     // When this is fired, function Start() should stop running 
     clearInterval(start); 
    }); 

}); 
+3

點擊事件處理程序永遠不會被執行(甚至連接),因爲'Start'永遠不會終止。 – 2012-03-20 17:54:47

+1

這不是事實!你不能有兩個方法在同一時間運行,它永遠不會「離開」'while'! – gdoron 2012-03-20 17:55:23

+0

感謝您指出,我已經注意到它,並正在修復它。 – mgibsonbr 2012-03-20 17:59:17

2

你可以矇混過關的東西用的setInterval() :

$(document).ready(function(){ 

    var intervalHolder;  

    $(function Start(){ 
     // Do Stuff on Ready 
     intervalHolder = setInterval("myTimedFunction()",1000); 
     // This runs "myTimedFunction()" every second 
    }); 

    $(document).on("click",".ExampleClick",function() { 
    // When this is fired, function Start() should stop running 
    clearInterval(intervalHolder); 
    }); 

}); 

function myTimedFunction() { 
    // Do groovy things every second 
}; 

這有點靈活,但可以達到類似的效果。

3

聽起來像是你有一個函數要反覆運行,然後停止它,當你點擊:

doStuff = function() { 
    // stuff to do regularly 
} 

$(document).ready(function(){ 

    // run doStuff every 2 seconds 
    var jobId = window.setInterval(doStuff, 2000); 

    // store the job id in a jquery data object 
    $('body').data("doStuffJobId", jobId); 

    // set up click hander for css class Example Click 
    $(".ExampleClick").click(function() { 
     // get the job id 
     var jobId = $('body').data("doStuffJobId"); 
     window.clearInterval(jobId); 
    }); 

}); 
+0

+1'setInterval'比我的'setTimeout'版本更好。 – meagar 2012-03-20 18:00:51