Jackson
Jackson

Reputation: 820

Javascript: setinterval start and stop function?

I'm tying to create stop and start functions for a setinterval.

I have been trying everything but I can't seem to get it right!

this is my code:

function myStartFunction() {
var myVar = setInterval(function(){ myTimer() }, 6000);

function myTimer() {

    $.ajax({
      type:"post",
      url:"myphppage.php",
      datatype:"html",
      success:function(data)
      {  
         if(data!="")
         {



         }
      }
    });

}

}

function myStopFunction() {
    clearInterval(myVar);
}

and this is how I've been trying to call them (This is how I NEED to call them):

to start it:

myStartFunction();

and to stop it:

myStopFunction();

but this is not correct and I know it.

could someone please advise on this issue as I've practically been pulling my hair out!

Thanks in advance.

Upvotes: 0

Views: 3110

Answers (2)

Robiseb
Robiseb

Reputation: 1606

Set myVar as a global variable like this

var myVar = 0;

function myStartFunction() {
  console.log('myStartFunction');
  myVar = setInterval(function(){ myTimer() }, 6000);

  function myTimer() {
    console.log('myTimer');
    /*
    $.ajax({
      type:"post",
      url:"myphppage.php",
      datatype:"html",
      success:function(data)
      {  
         if(data!="")
         {



         }
      }
    });
    */
    
    // FOR TEST
    myStopFunction();
  }

}

function myStopFunction() {
  console.log('myStopFunction');
  clearInterval(myVar);
}


// FOR TEST
myStartFunction();

Upvotes: 2

Andrea Sessa
Andrea Sessa

Reputation: 898

Declare myVar as global (outside the functions), cause in your example myStopFunction can't see it.

var myVar;

function myStartFunction() {
    myVar = setInterval(function(){ myTimer() }, 6000);
}

function myTimer() {
    $.ajax({
      type:"post",
      url:"myphppage.php",
      datatype:"html",
      success:function(data)
      {  
         if(data!="")
         {
         }
      }
    });
}

function myStopFunction() {
    clearInterval(myVar);
}

Upvotes: 4

Related Questions