[英]Defer A Function for 24 Hours
我試圖使一次單擊后的功能暫時無法工作(24小時)。
我嘗試將整個事情包裝在setTimeout()函數中,將ms計數設置為86400000。
(請參見此處的輸出)
$('.dates').click(function() {
var rand = Math.floor(Math.random() * 100 + 1);
var flows = ["flowOne", "flowTwo", "flowThree"];
var colors = ["colOne", "colTwo", "colThree", "colFour", "colFive", "colSix"];
var timing = (Math.random() * (1.3 - 0.3) + 1.6).toFixed(1);
// Animate Particle
$('<div class="particle part-' + rand + ' ' + colors[Math.floor(Math.random() * 6)] + '" style="font-size:' + Math.floor(Math.random() * (30 - 22) + 22) + 'px;"><i class="fa fa-heart-o"></i><i class="fa fa-heart"></i></div>').appendTo('.particle-box').css({
animation: "" + flows[Math.floor(Math.random() * 3)] + " " + timing + "s linear"
});
$('.part-' + rand).show();
// Remove Particle
setTimeout(function() {
$('.part-' + rand).remove();
}, timing * 1000 - 100);
$('#output').html(function(i, val) {
return parseInt(val, 10) + 1;
console.log(val);
});
return false;
});
有什么我想念的嗎?
如何推遲該函數,使其只能每24小時調用一次?
為了防止某個函數執行,而又不更改應用程序其余部分與該函數的交互方式,您需要使用某種標志或布爾條件。
例如:
$('.dates').click(function() {
if (!isActive) {
return;
}
// rest of your code
});
現在,從當前時間開始計算24小時的最簡單方法可能是使用Date.now
檢索以毫秒為單位的當前時間,然后將24小時(以毫秒為單位)添加到該值。
// Calculate 24 hours in milliseconds
var second = 1000;
var minute = 60 * second;
var hour = 60 * minute;
var day = 24 * hour;
var now = Date.now();
var tomorrow = now + day;
鑒於您要等待多長時間,您可能需要將其保存在localStorage
:
localStorage.setItem('next-active-time', tomorrow);
現在,您要做的就是更改激活功能的方式。 而不是使用簡單的標志,而是在本地存儲中檢查下一個值,並僅在以下情況下激活
$('.dates').click(function() {
// default to 0 when it hasn't been set
var nextActiveTime = localStorage.getItem('next-active-time') || 0;
if (Date.now() < nextActiveTime) {
return;
}
// rest of your code
// make sure to update local storage at this point
});
從理論上講,您可以使用lodash的節流閥 (或類似的實現方式)完成您想要做的事情,但是在我看來,這就像您在瀏覽器中進行編程一樣,因此強制執行這24小時規則是不可能的(用戶可以在以下位置刷新頁面任何時候)。 照這樣說:
我希望這可以使事情變得簡單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.