Ahad Ahad - 28 days ago 24
Javascript Question

Dynamic setInterval in Javascript

I am going to setup a timer for different events dynamically in HTML.
There is a function to generate an HTML elements when ajax completed as below:

function buildOnlineQuizIns(courseId, onlineQuizes) {
var items = '';
var d = new Date();
var timeStamp = d.getTime();
$.each(onlineQuizes, function (key, value) {
var date1 = new Date(value['startDate']);
var t1 = date1.getTime()+value['offsetTime']*60*1000;
var date2 = new Date(value['endDate']);
var t2 = date2.getTime()+value['offsetTime']*60*1000;

var startDate = convertDate(value['startDate'], value['offsetTime']);
var endDate = convertDate(value['endDate'], value['offsetTime']);
items += '<table id="quizOnlineItem'+value['qsClassId']+'" class="quizOnlineItem">' +
'<tr><td style="color: #0000cb; font-weight: bold; width: 70px;">Quiz Set:</td><td style="margin-left: 10px;">'+value['name']+'</td></tr>' +
'<tr><td style="margin-right: 10px; color: #0000cb; font-weight: bold;">Header:</td><td>' + value['quizHeader'] + '</td></tr>' +
'<tr><td style="margin-right: 10px; color: #00B300; font-weight: bold;">Start Date:</td><td>' + startDate + '</td></tr>' +
'<tr><td style="margin-right: 10px; color: #DB3315; font-weight: bold;">End Date:</td><td>' + endDate + '</td></tr>' +
'</table>' +
'<div id="countdown'+value['qsId']+'" class="timer">test</div>';
var timeLeft = '';
if(timeStamp<t1){
seconds[value['qsId']] = t1 - timeStamp;
countdownTimer[value['qsId']] = setInterval(timer(value['qsId']), 1000);
}else if(timeStamp>t1 && timeStamp<t2){
seconds[value['qsId']] = t2 - timeStamp;
countdownTimer[value['qsId']] = setInterval(timer(value['qsId']), 1000);
}
});
return items;


}

and there is a function for timer as below:

var countdownTimer = [];
var seconds = [];
function timer(qsId) {
alert(countdownTimer[qsId]);
var days = Math.floor(seconds[qsId]/24/60/60);
var hoursLeft = Math.floor((seconds[qsId]) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds[qsId] % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
$('#countdown'+qsId).html(days + "day " + hours + ":" + minutes + ":" + remainingSeconds);
if (seconds[qsId] == 0) {
clearInterval(countdownTimer[qsId]);
$('#countdown'+qsId).html("Completed");
} else {
seconds[qsId]--;
}
}


However, nothing updates when page loaded. Anyone can help me in this matter please. Thanks!!!

Answer

When you pass a function to setInterval, you must pass the function without calling it:

This call the function when this line is executed:

setInterval(timer(value['qsId']), 1000);

This call the function only after 1s:

setInterval(function() {
    timer(value['qsId'])
}, 1000);

Ps: Didn't check if this was the problem, but I think it will be a problem anyways.