「點擊取得驗證碼後 60 秒內不得再次發送」幾乎每個註冊或登入頁都會用到。單靠前端計時器並不嚴謹——使用者一按 F5,計時就歸零了。搭配 jquery.cookie 外掛把剩餘秒數寫進 cookie,就能連重新整理一起擋下來。

先到官方網站(https://plugins.jquery.com/cookie/)下載 cookie 外掛並放進專案目錄,然後在頁面中依序載入 jQuery 與 jquery.cookie.js。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Examples</title>
<script src="https://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="jquery.cookie.js"></script>
<style type="text/css">
* {margin: 0; padding: 0; font-family: "Microsoft Yahei";}
.captcha-box {width: 360px; height: 34px; margin: 30px; padding: 30px;
border: #956E6F 1px dashed; border-radius: 5px; background-color: #FAF2F2;}
#mobile { float: left; width: 180px; height: 32px; border: #e5e5e5 1px solid;
line-height: 32px; text-indent: 8px; outline: none;}
#getting {float: left; height: 34px; margin-left: -1px; padding: 0 18px;
text-align: center; line-height: 34px; border: #e5e5e5 1px solid;
background: linear-gradient(0deg, #f4f2f2 0%,#fbf9f9 100%);
cursor: pointer; outline: none;}
</style>
<script>
$(function(){
/* 仿刷新:檢測是否存在 cookie */
if($.cookie("captcha")){
var count = $.cookie("captcha");
var btn = $('#getting');
btn.val(count+'秒後可重新獲取').attr('disabled',true).css('cursor','not-allowed');
var resend = setInterval(function(){
count--;
if (count > 0){
btn.val(count+'秒後可重新獲取').attr('disabled',true).css('cursor','not-allowed');
$.cookie("captcha", count, {path: '/', expires: (1/86400)*count});
}else {
clearInterval(resend);
btn.val("獲取驗證碼").removeClass('disabled').removeAttr('disabled style');
}
}, 1000);
}
/* 點擊改變按鈕狀態,這裡簡略掉 ajax 發送簡訊驗證的程式碼 */
$('#getting').click(function(){
var btn = $(this);
var count = 60;
var resend = setInterval(function(){
count--;
if (count > 0){
btn.val(count+"秒後可重新獲取");
$.cookie("captcha", count, {path: '/', expires: (1/86400)*count});
}else {
clearInterval(resend);
btn.val("獲取驗證碼").removeAttr('disabled style');
}
}, 1000);
btn.attr('disabled',true).css('cursor','not-allowed');
});
});
</script>
</head>
<body>
<div class="captcha-box">
<input type="text" id="mobile" maxlength="11" placeholder="請輸入手機號碼">
<input type="button" id="getting" value="獲取驗證碼">
</div>
</body>
</html>
整個實作可以拆成兩條路徑。第一條是頁面載入時的檢查:讀取名為 captcha 的 cookie,若存在就代表使用者剛發送過,於是直接把按鈕設為 disabled,並依 cookie 中記下的剩餘秒數繼續倒數,同時在每次遞減時同步更新 cookie 的存活時間。
第二條是按鈕點擊事件:把倒數從 60 啟動,每秒更新文案與 cookie,歸零後清除計時器並還原按鈕狀態。真正的簡訊發送請求就插在這裡呼叫你的 Ajax 介面。
這裡有個小細節值得注意:expires: (1/86400)*count 是利用 cookie 的 expires 以「天」為單位,把剩餘秒數換算成天數,讓 cookie 的生命週期與倒數同步結束。
前端計時器與 cookie 都只是使用者體驗層面的防護,懂開發的人清除 cookie 或直接呼叫介面就能繞過。真正的頻率限制一定要在伺服器端實作,例如以手機號碼為 key 記錄最後發送時間、搭配短時間內的請求次數上限,並把驗證碼的效期與核對邏輯放在後端。前端負責讓操作順手,後端負責守住底線,兩者相輔相成。