我需要在特定時間間隔後顯示彈出窗口,其中倒數計時器運行5分鐘,如果在倒計時變爲0:00之前沒有互動,則會重定向到某個網址。我已經爲此寫了下面的js函數,但是它在計時器運行時爲負數或停止執行時有問題!下面是代碼 -JavaScript定時器|隨機行爲
function displayOnTimeOut() {
window.docTitle = document.title;
var outputText = AdfPage.PAGE.findComponent('root:popupTxt');
outputText.setValue(' ');
var timerInitDate = new Date();
var endTime = timerInitDate.getMinutes() * 60 + timerInitDate.getSeconds() + 300;
function displayCountdown() {
var d = new Date();
var timeNow = d.getMinutes() * 60 + d.getSeconds();
var timeleft = endTime - timeNow;
var seconds = timeleft % 60;
var minutes = Math.floor(timeleft/60);
var minutesText = " minutes";
if (minutes == 1) {
minutesText = " minute";
}
var secondsText = " seconds";
if (seconds == 1) {
secondsText = " second";
}
if (seconds > 1 && seconds % 2 == 0) {
document.title = document.title == docTitle ? 'News Flash' : docTitle;
}
if (timeleft == 0) {
clearInterval(timerIntervalId);
window.onbeforeunload = null;
outputText.setValue(' ');
window.location.href = '/some/url.jspx';
return;
} else {
outputText.setValue(minutes + minutesText + " and " + seconds + secondsText);
}
}
window.timerIntervalId = setInterval(displayCountdown, 1000);
var popup = AdfPage.PAGE.findComponentByAbsoluteId('root:popup');
popup.show();
}
var timeOutPeriod = 60 * 1000;
if (typeof timerTimeoutId !== 'undefined') {
clearTimeout(timerTimeoutId);
}
if (typeof timerIntervalId !== 'undefined') {
clearTimeout(timerIntervalId);
}
window.timerTimeoutId = setTimeout(displayOnTimeOut, timeOutPeriod);
請忽略如何/時,這就是所謂的,我需要的時候使用ExtendedRenderKitService
調用。 我不是JS編碼方面的專家,因爲上面的代碼很明顯,請有人看看?
非常感謝。
謝謝!
'如果(的timeleft <= 0)' – lujcon 2015-02-10 20:47:10
由於lujcon,然而,我調用'clearInterval'如果'timeleft'變得'0',所以它永遠不應該大於0少,是嗎?還爲此添加了'return'語句。 – 2015-02-10 20:51:26
這不是真的。每隔1秒setInterval並不意味着它會每秒執行一次。它可以是每1001毫秒...所以你可以有1秒左和下一個迭代-1秒左... – lujcon 2015-02-10 20:53:31