开发者

Impose a wait between two submits

开发者 https://www.devze.com 2023-04-01 05:41 出处:网络
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.

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); 
         subm开发者_开发问答it_timestamp = timestamp_message ;

          //AJAX ACTION             

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


return false;   
});


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(); 
});


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();
  }
});


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消