Rate limiting to prevent malicious behavior in ExpressJS

烂漫一生 提交于 2019-12-01 03:54:40

You could use the Collate object in your webpage.

function Collate(timeout) {
  this.timeout = timeout || 1000;
}
Collate.prototype = {
  time: 0,

  idle: function() {
    var t = new Date().getTime();
    return (t - this.time > this.timeout && (this.time = t));
  },

  prefer: function(func) {
    this.func = func;
    clearTimeout(this.timer);
    this.timer = setTimeout(func, this.timeout);
  }
};

If you want a function to run once and not run again within the next 1 second. Like if you want to prevent the user from submitting a form many times, you do this:

var timer = new Collate(3000);  //3 seconds
button1.onclick = function() {
    if(timer.idle()) {
        button1.form.submit();
    } else alert("Don't click too quickly!");
}

//or on the form tag

<script>var submitTimer = new Collate(3000);</script>
<form action="post" onsubmit="return submitTimer.idle();">

If you expect an event to fire multiple times and only want to react to the last time it fires. Like if you want to search after a user has finished typing, you do this:

var timer = new Collate(700); //0.7 seconds
textfield1.onkeyup = function() {
    timer.prefer(function() {
        autocomplete.search(textfield1.value);
    });
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!