2012-03-20 108 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