TechTimeGames TechTimeGames - 3 months ago 5
Javascript Question

Interval wont stop when button clicked

My interval wont stop, when i click my submit button, and then start the interval afterwards.

Im making a chat system, that's supposed to reload the chat over and over again, but the message submit is VERY slow when the chat reload is running, so its supposed to stop the chat reloading when the message submitting is running, and then start again afterwards.

Script:

<script>
$(document).ready(function(){
function auto_load(){
$.ajax({
url: "index.php?url=userchat1&id=1",
cache: false,
success: function(data){
$("#chatdiv").html(data);
}
});
}
auto_load();
//Refresh auto_load() function after 500 milliseconds
var myVar = setInterval(function(){ auto_load() }, 500);

$('#beskedform').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'index.php?url=chatsubmit&id=1',
data: $('#beskedform').serialize(),
success: function () {
$("#msg").attr('value','');
$("#msg").removeAttr('disabled');
$("#msgbutton").removeAttr('disabled');
var myVar = setInterval(function(){ auto_load() }, 500);
}
});
clearInterval(myVar);
$("#msg").attr('disabled','disabled');
$("#msgbutton").attr('disabled','disabled');

});
});
</script>


HTML:

<form id="beskedform">
<textarea name="msg" id="msg" class="form-control content-group" rows="3" cols="1" placeholder="Skriv din besked..."></textarea>

<div class="row">
<div class="col-xs-6">
</div>

<div class="col-xs-6 text-right">
<button type="submit" id="msgbutton" class="btn bg-teal-400 btn-labeled btn-labeled-right"><b><i class="icon-circle-right2"></i></b> Send</button>
</div>
</div>
</form>

Answer

Please, use this script.

<script>
$(document).ready(function(){
 function auto_load(){
    $.ajax({
      url: "index.php?url=userchat1&id=1",
      cache: false,
      success: function(data){
         $("#chatdiv").html(data);
      } 
    });
  }
  auto_load();
  //Refresh auto_load() function after 500 milliseconds
  var myVar = setInterval(function(){ auto_load() }, 500);

    $('#beskedform').on('submit', function (e) {      
          e.preventDefault();
          $.ajax({
            type: 'post',
            url: 'index.php?url=chatsubmit&id=1',
            data: $('#beskedform').serialize(),
            success: function () {
                $("#msg").attr('value','');
                $("#msg").removeAttr('disabled');
                $("#msgbutton").removeAttr('disabled');
                myVar = setInterval(function(){ auto_load() }, 500);
            }
      });
      clearInterval(myVar);
      $("#msg").attr('disabled','disabled');
      $("#msgbutton").attr('disabled','disabled');  

    });
});

Comments