user1753631
user1753631

Reputation: 5

jquery prevent function running more than once

mySepsisTimer (a simple countdown timer) initiates once option select criteria (sepsis-six-sirs) are reached. But, if a user clicks on another select option after starting the timer function, a duplicate clock also runs. How can I prevent the mySepsisTimer function from running more than once, or reset it if the user clicks (or unselects) another one of the same (sepsis-six-sirs) options.

$('#sepsis-six-sirs input[type=checkbox]').change(function(){
recalculateThisIsSepsis();
});

function recalculateThisIsSepsis(){
var sum = 0;
$("#sepsis-six-sirs input[type=checkbox]:checked").each(function(){
    sum+=parseInt($(this).val());
});

if (sum > 1) {
    mySepsisTimer();
}}

Upvotes: 0

Views: 1250

Answers (3)

Amit
Amit

Reputation: 46323

If all you want is to limit mySepsisTimer to 1 time, you can simply use a flag on on the global scope.

var onlyOneTimer = 0;

// ... The rest of your code ...

if (sum > 1 && onlyOneTimer == 0) {
     onlyOneTimer = 1;
     mySepsisTimer();
}}

It's not a "Best Practice" solution, but it's the simplest to understand.

Upvotes: 0

guest271314
guest271314

Reputation: 1

Try utilizing $.Callbacks("once")

var callbacks = $.Callbacks("once");

callbacks.add(mySepsisTimer);

$('#sepsis-six-sirs input[type=checkbox]').change(function() {
  recalculateThisIsSepsis();
});

function recalculateThisIsSepsis(){
  var sum = 0;
  $("#sepsis-six-sirs input[type=checkbox]:checked").each(function() {
    sum+=parseInt($(this).val());
  });

  if (sum > 1) {
    callbacks.fire();
  }
}

Upvotes: 1

Darcey Mckelvey
Darcey Mckelvey

Reputation: 556

It's simple using on and off.

on() -> add an evend handler off() -> remove an event handler

Example:

$("#item li").on('click', function () {
    $(this).text('ITEM CLICKED')
    alert('CLICKED');

    //remove the event
    $(this).off("click")
});

Upvotes: 1

Related Questions