Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return False / Stop jQuery Function on click

Tags:

jquery

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?

like image 426
Joe Avatar asked Dec 12 '25 01:12

Joe


2 Answers

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;
  });

});
like image 162
meagar Avatar answered Dec 14 '25 18:12

meagar


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);
    });

});
like image 25
Doug Harris Avatar answered Dec 14 '25 20:12

Doug Harris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!