views:

58

answers:

4

So here's my problem:

I've got one function that runs every 15 seconds. It checks to see if new comments have been added to a page.

I've got a form that submits a new comment once the submit button is pressed, then displays the new comment on the page.

In the process of adding a new comment, the "checkEvery15Seconds" function is querying the database at the same time, so I end up with duplicate comments on the page (not in the database though, this is purely a javascript issue).

How can I get my "submitComment" function to stop the "checkEvery15Seconds" function and restart it after the "submitComment" function has finished executing?

A: 

Wrap it up in an object that allows other functions to set start/stop flags on it.

function My15SecondsObj() {
    var objSelf = this;

    // 
    this.run();
}

My15SecondsObj.Paused = false;
My15SecondsObj.prototype.run= function() { 
   if (!Paused)
   {
      // Do your call here
   }
   var _this = this;
   setTimeout(function() { _this.run(); }, 15000);

}

Now when you want to use this object, just do

var myObj = new My15SecondsObj();

and when you want to pause it,

myObj.Paused = true;

and start it again by doing:

myObj.Paused = false;

Add some events if you want to get really crazy, so that other objects can subscribe to notifications about when the database updates have succeeded, etc...

womp
A: 

Simplest solution: use a flagging variable that you turn on and off. The first line of your "checkEvery15Seconds" function reads: if (!global_checkingEvery15Seconds) return;

Just set that variable (whatever you name it, global or object-bound) to true when you want the checking turned on, and off when you don't.

Plynx
+2  A: 

add a boolean called somewhat suspend15sCheck in a scope which is accessible by both functions. enable it while adding the comment and afterwards set it to false again.

in your 15sCheck-function you first have to check if you are allowed to check :-)

var suspend15sCheck = false;

function addComment()
{
  suspend15sCheck = true;

  // add comment on base of form data

  suspend15sCheck = false;
}

function myTimer()
{
    if(suspend15sCheck === false) 
    {

      // add comments via ajax request
      // remember to check if the comments who will be added already exist :-)

    }
}
henchman
that's exactly what i want to do. how do I create a global variable like that?
Andrew
just declare it out of every other function, then you can access it globaly.
henchman
would you mind showing an example? I'm not very javascript savvy.
Andrew
A: 

You'll need a status variable to indicate the current state of the comment ajax request

var requestComments = false;

if(requestComments === false) {
  requestComments = true;
  // make ajax request

  // on ajax success/fail
  requestComments = false;
}
Ben Rowe