我知道有很多关于setInterval的问题,尤其是关于它只能运行一次的问题,我已经关注了他们,但是没有得到任何可以帮助我的信息。 Q1,Q2,Q3,Q4等...
Becoz我多次使用setInterval()
,我必须分别控制每个运行的事件,我发现了一个有用的博客文章,内容涉及处理多个setInterval
事件。 http://clarkeulmer.com/handling-multiple-timers-with-javascripts-setinterval-and-jquery/
在以下屏幕截图中,您可以看到我正在尝试执行的操作。单击“杀死”按钮后,应该出现倒数计时。
按照上面提到的教程,我编写了以下代码:
$('tbody a.killed').click(function(){
// Adds 30 min to current time
var respawnTime = moment().add(30, 'minutes').format('HH:mm:ss');
// Sets countdown for 30 min
var eventTime = moment().add(30, 'minutes').unix();
var currentTime = moment().unix();
var diffTime = eventTime - currentTime;
var duration = moment.duration(diffTime * 1000, 'milliseconds');
var that = this;
function respawnTimeCountdown(){
duration = moment.duration(duration.asMilliseconds() - 1000, 'milliseconds');
var h = moment.duration(duration).hours(),
m = moment.duration(duration).minutes(),
s = moment.duration(duration).seconds();
h = $.trim(h).length === 1 ? '0' + h : h;
m = $.trim(m).length === 1 ? '0' + m : m;
s = $.trim(s).length === 1 ? '0' + s : s;
if (duration > 0){
// Removes time from the table if it exists
if($(that).parent().prevAll(':eq(0)').has('p')) {
$(that).parent().prevAll(':eq(0)').children().remove();
}
// show how many hours, minutes and seconds are left
$(that).parent().prevAll(':eq(0)').append("<p>" + h + ":" + m + ":" + s + "</p>");
}
else {
// Removes time from the table if it exists
if($(that).parent().prevAll(':eq(0)').has('p')) {
$(that).parent().prevAll(':eq(0)').children().remove();
}
$(that).parent().prevAll(':eq(0)').append("<p>" + "<b class='fight'>" + "⚔" + "</b>" + "</p>");
}
}
var intervalId = setInterval(respawnTimeCountdown(), 1000);
if(diffTime > 0) {
$(this).parent().prevAll(':eq(0)').children().attr('data-timer-id', intervalId)
}
// Add class 'disabled' to button "Killed" to prevent multiple event calls
if($(this).parent().prevAll(':eq(0)').children().has('p')) {
$(this).addClass('disabled');
}
// Removes time from the table if it exists
if($(this).parent().prevAll(':eq(1)').has('p')) {
$(this).parent().prevAll(':eq(1)').children().remove();
}
// Puts re-spawn time in the table.
$(this).parent().prevAll(':eq(1)').append("<p>"+respawnTime+"</p>");
});
这是我的DOM:
<tbody>
<tr>
<th>1</th>
<td></td>
<td></td>
<td>
<a class="killed right waves-effect waves-light btn-small blue-grey">Killed</a>
<a style="margin-right: 5px" class="clear right waves-effect waves-light btn-small orange">Clear</a>
</td>
</tr>
<tr>
<th>2</th>
<td></td>
<td></td>
<td>
<a class="killed right waves-effect waves-light btn-small blue-grey">Killed</a>
<a style="margin-right: 5px" class="clear right waves-effect waves-light btn-small orange">Clear</a>
</td>
您可以在以下链接https://l2ob.netlify.com/上找到此工具 使用浏览器开发工具进行测试很容易。