Anon
Anon

Reputation: 1221

Impose a wait between two submits

I have a form which does an AJAX action when submitting. Just after a user has submitted the form, I'd like to impose a minimal waiting time of 5sec to post one more time.

What the better way ? I made this script (doesn't work but I guess idea is here):

$("form#submit_under_wall"+array[1]).submit(function() {

    var submit_timestamp=0;
    var c = new Date();
    var now = ISODateString(c); 

    if(now-submit_timestamp>5){

         var d = new Date();
         var timestamp_message = ISODateString(d); 
         submit_timestamp = timestamp_message ;

          //AJAX ACTION             

    }else{ alert("Wait 5sec between each post."); }


return false;   
});

Upvotes: 1

Views: 125

Answers (3)

vol7ron
vol7ron

Reputation: 42109

use window.setTimeout()

  1. Wrap what you want to do in a function (eg function foo (){ alert('test'); })

  2. Call it with a 5 second delay setTimeout(foo,5000)

Upvotes: 0

mkoryak
mkoryak

Reputation: 57948

This doesnt work because the timestamp is reset every time they submit, you need to move submit_timestamp outside of the function. Also, that 5 should probably be 5 * 1000

something like this (not tested):

var submitTime = (new Date()).getTime() - 5000; //let user submit if he clicks within 5s of page load
$("form#submit_under_wall"+array[1]).submit(function(e) {
    var now = (new Date()).getTime();
    if(now-submitTime > 5000){
         submitTime = (new Date()).getTime();
         //AJAX ACTION             
    } else {
        alert("Wait 5sec between each post.");
    }
    e.preventDefault(); 
});

Upvotes: 2

Arnaud Leymet
Arnaud Leymet

Reputation: 6132

The easiest and most standard way would be to use Javascript native setTimeout method.

var last_action;

function ajax_action() {
  last_action = Date.getTime();
  // AJAX STUFF
}

$("form#submit_under_wall"+array[1]).submit(function(e) {
  e.preventDefault(); // Sexier than 'return false'
  if(last_action != undefined) {
    setTimeout(ajax_action, Date.getTime()-last_action); // Wait for 5s before doing the action 
  } else {
    ajax_action();
  }
});

Upvotes: 0

Related Questions