gpt4 book ai didi

javascript在倒计时中显示秒数

转载 作者:行者123 更新时间:2023-11-30 09:51:23 25 4
gpt4 key购买 nike

我有一个弹出的模态窗口,让用户知道他的 session 将在 N 秒后到期。我想做的是向用户显示剩余时间,因此消息将类似于

"Your session is about to expire in 2 minutes" // if remaining time is more than 1 minute, then display it in minutes else in seconds - if possible
...
"Your session is about to expire in 50 seconds"
...
"Your session is about to expire in 15 seconds"
...

这是我的代码

<div class="modal-content">

<div class="modal-header">
<span class="close">×</span>
<h2>Session timeout</h2>
</div>

<div class="modal-body">
<p>Your session is about to expire in <span id="time-remain"></span> and you will be logged out.</p>
<p><button class="btn blue" id="extend-session">Extend Session</button></p>
</div>

</div>

这是javascript

var modal = document.getElementById('session-timeout');
var timeCount = document.getElementById('time-remain');
var span = document.getElementsByClassName("close")[0]; // Get the <span> element that closes the modal
var extendSession = document.getElementById("extend-session"); // Get the extend button
var sessionTimeout = <?php echo config_item('session-timeout'); ?>; // set timeout - temporarily set to 4 mins ( i.e. 240000 ms)

var interval;

function countDown(time) {

var unit = 'seconds';

interval = setInterval(function () {
if (time <= 0) {

// logout when session expires
setTimeout(function () {
alert('Logout!');
// window.location = "<?php echo admin_url('auth/logout'); ?>";
}, time);


clearInterval(interval);
}

// reduce each second
time = time - 1000;
timeVal = (time / 1000) % 60;

if (time >= 60) {
// if time (seconds) are 60 or more show time as minutes
unit = 'minutes';
timeVal = Math.floor(timeVal / 60);
}

timeCount.innerHTML = timeVal + ' ' + unit;

}, 1000);
}

// Show the modal window in last 2 minutes
function modalPopUp(time) {
var remainingTime = time - 120000; // in my example is 240000 - 120000 (i.e. 4-2=2 mins)

setTimeout(function() {

// show modal
modal.style.display = 'block';
countDown(remainingTime);

}, remainingTime);
}

function sessionExpire(time) {
modalPopUp(time);
}

我怎样才能正确地完成这项工作?

最佳答案

setInterval 需要一个回调函数作为第一个参数:setInterval(函数,MS 中的间隔)

您可以尝试的是:

  • 创建一个变量来保存时间直到 session 过期(var secondsRemaining)
  • 在 1000MS(1 秒)上创建一个间隔
  • 在间隔回调中,将secondsRemaining减1
  • 显示 secondsRemaining#time-remain 范围内的值

为了让它更花哨,更适合您的示例,您可以检查是否在间隔回调中显示 剩余秒数剩余分钟数

如果 secondsRemaining 大于 60,则您还剩 secondsRemaining/60 分钟。

在这个例子中我使用了 100MS 的间隔所以你不需要等待几分钟:)

https://jsfiddle.net/upkmg80r/2/

关于javascript在倒计时中显示秒数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36328482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com