简体   繁体   中英

Delay Javascript button onClick using setTimeout

I'm having a problem with delaying a button click. I've already searched through stackoverflow and I've found a couple answers and it's easy enough with setTimeout but I can't get it to work in what I'm working on. Here's a sample of the code:

AJAX submits the data to a database on submit button click

<script>
  $(function () {
    $('form').on('submit', function (e) {
      $.ajax({
        type: 'post',
        url: 'post.php',
        data: $('form').serialize(),
      });
      e.preventDefault();
    });
  });
</script>

Pusher code

<script>
    $(function() {

    var pusher = new Pusher('pusher')
    var activityChannel = pusher.subscribe('stream');
    var activityMonitor = new PusherActivityStreamer(activityChannel, "#current");

    var examples = new ExampleActivities(activityMonitor, pusher);

    $("#broadcast").click(function(){
        activityMonitor.sendActivity('broadcast');
    });
    $("#submit").click(function(){
        activityMonitor.sendActivity('submit');
    });
    });
</script>

HTML buttons

<input id="submit" name="submit" type="submit" value="Submit" onclick="addMEM()"><br>
<button id="broadcast">Broadcast</button>

The onclick="addMEM()" on the submit button is for another script. It's a pretty busy button.

So what's happening is I click Submit and the ajax script pushes the data to post.php which submits it to a database. With that same Submit click the Pusher code is triggered which eventually pulls that submitted data back out of the database and broadcasts it to everyone that's connected.

The problem I'm having is that Submit submits the data to the database and it triggers the Pusher which pulls from the database simultaneously. 75% of the time the pusher code tries to pull the data from the database before the Submit has submitted it.

I put the setTimeout everywhere I could think of and just couldn't delay the Pusher code. Any suggestions? It's ok if the Submit AND Broadcast buttons are delayed. It's not ok if clicking Submit delays the AJAX code or the onclick=addMEM()

Sorry for making this so complicated. This is the final step of a long project and if I can get this working then it's all CSS, data entry and math from here.

I suggest passing a success callback to jQuery.ajax method that would trigger broadcasting like so:

$.ajax({
  type: 'post',
  url: 'post.php',
  data: $('form').serialize(),
  success: function () {
    activityMonitor && activityMonitor.sendActivity('broadcast');
  }
});

A solution with setTimeout would look like this:

$("#broadcast").click(function(){
    setTimeout(function () { activityMonitor.sendActivity('broadcast') }, 2000);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM