I have function Start() that is fired on ready. When I click on .ExampleClick, I want to stop function Start() from running. Here is my example...
$(document).ready(function(){
$(function Start(){
// Do Stuff on Ready
});
$(document).on("click",".ExampleClick",function() {
// When this is fired, function Start() should stop running
});
});
What is the best method to achieve what I am trying to do?
If Start is looping forever, your browser will hang. JavaScript functions cannot truly run in parallel. Assuming that Start is indeed some background process that is meant to loop forever, you'll need to re-think things so that it executes once and then schedules itself to execute again some point in the future, allowing other events to be handled.
Each time Start executes, it can examine some state maintained by the on-click handler to decide whether or not it should run and enqueue itself again:
$(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;
});
});
Sounds like you have a function you want to run repeatedly and then stop it when you click:
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);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With