У меня есть форма динамических c данных, у каждого из моих данных есть таймер (обратный отсчет), когда я нажимаю, и go до следующих страниц таймер будет конфликтовать со старыми данными (новый таймер и старый таймер будут перекрывать друг друга )
Запись экрана
Как видите, мои первые данные имеют таймер 35 seconds
и второй таймер 2 minutes
они перекрываются на второй странице.
Код
var index = 0;
$("#clicks").click(function(){
// timer function
function timer(seconds, countdownTimer, callback) {
var days = Math.floor(seconds / 24 / 60 / 60);
var hoursLeft = Math.floor((seconds) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Times Up!";
$("#clicks").attr("disabled", true);
$("#clicks").hide();
$('.answerPanel').html('<div class="text-center text-danger">OH NO! <br> Times Up!</div>');
} else {
seconds--;
}
//Pass seconds param back to the caller.
callback(seconds);
}
//We pass the countdownTimer param into the timer function as well.
var countdownTimer = null,
seconds = data.quizzes[index].quiz_time;
countdownTimer = setInterval(function() {
timer(seconds, countdownTimer, function(_seconds){
seconds = _seconds;
})
}, 1000);
// printing function
if(typeof data.quizzes[index] != 'undefined'){
var html = '<div class="row"><div class="col-md-12"><div class="pull-left questionTitle">'+data.quizzes[index].question+'</div><div class="pull-right" id="countdown"></div></div></div>';
if(data.quizzes[index].choices.length > 0){
html+='<div class="col-md-12">';
if(data.quizzes[index].question_type == 'multiple'){
data.quizzes[index].choices.forEach((element, index, array) => {
html+='<div class="checkbox checkbox-primary">';
html+='<input id="choice" name="choice" type="checkbox" value="'+element.choice+'" required>';
html+='<label for="checkbox2">'+element.choice+'</label>';
html+='</div>';
});
} else {
data.quizzes[index].choices.forEach((element, index, array) => {
html+='<div class="radio radio-primary">';
html+='<input id="choice" name="choice" type="radio" value="'+element.choice+'" required>';
html+='<label>'+element.choice+'</label>';
html+='</div>';
});
}
html+='</div>';
}
$(".answerPanel").html(html);
index++;
}
if(data.quizzes.length > index+1) {
$("#clicks").html("Next");
}
if(data.quizzes.length === index) {
$("#clicks").html("Send");
$('#clicks').removeClass('btn-primary').addClass('btn-success saveAnswers');
}
//end of printing function
});
Есть идеи?
Обновление
Для лучшего расследования вот мой полный сценарий
<script>
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var table = $("#projectTable").DataTable({
'createdRow': function(row, data, dataIndex) {
if (dataIndex == 0) {
$(row).addClass('selected');
};
setTimeout( function () {
table.draw();
}, 100 );
}
});
$('#projectTable tbody').on( 'click', 'tr', function (e) {
e.preventDefault();
$('.projectName').empty();
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
$('.projectName').empty();
var projectId = $(this).data('id');
//quizzes
$.ajax({
type:'GET',
url:'{{url('dashboard/getQuizzeswithChoices')}}/'+projectId,
beforeSend: function(data) {
console.log("click - ajax before send", data);
},
success:function(data){
$('.answerPanel').html('');
$('#clicks').html("Next");
$('#clicks').removeClass('btn-success saveAnswers').addClass('btn-primary');
$('.projectName').append('of ', data.project.name);
console.log(data);
//return existed data to quizzes
var index = 0;
var countdownTimer = null;
$("#clicks").click(function(){
// timer function
function timer(seconds, countdownTimer, callback) {
var days = Math.floor(seconds / 24 / 60 / 60);
var hoursLeft = Math.floor((seconds) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Times Up!";
$("#clicks").attr("disabled", true);
$("#clicks").hide();
$('.answerPanel').html('<div class="text-center text-danger">OH NO! <br> Times Up!</div>');
} else {
seconds--;
}
//Pass seconds param back to the caller.
callback(seconds);
}
//We pass the countdownTimer param into the timer function as well.
if (countdownTimer != null) {
clearInterval(countdownTimer);
}
seconds = data.quizzes[index].quiz_time;
countdownTimer = setInterval(function() {
timer(seconds, countdownTimer, function(_seconds){
seconds = _seconds;
})
}, 1000);
// printing function
if(typeof data.quizzes[index] != 'undefined'){
var html = '<div class="row"><div class="col-md-12"><div class="pull-left questionTitle">'+data.quizzes[index].question+'</div><div class="pull-right" id="countdown"></div></div></div>';
if(data.quizzes[index].choices.length > 0){
html+='<div class="col-md-12">';
if(data.quizzes[index].question_type == 'multiple'){
data.quizzes[index].choices.forEach((element, index, array) => {
html+='<div class="checkbox checkbox-primary">';
html+='<input id="choice" name="choice" type="checkbox" value="'+element.choice+'">';
html+='<label for="checkbox2">'+element.choice+'</label>';
html+='</div>';
});
} else {
data.quizzes[index].choices.forEach((element, index, array) => {
html+='<div class="radio radio-primary">';
html+='<input id="choice" name="choice" type="radio" value="'+element.choice+'">';
html+='<label>'+element.choice+'</label>';
html+='</div>';
});
}
html+='</div>';
}
$(".answerPanel").html(html);
index++;
}
if(data.quizzes.length > index+1) {
$("#clicks").html("Next");
}
if(data.quizzes.length === index) {
$("#clicks").html("Send");
$('#clicks').removeClass('btn-primary').addClass('btn-success saveAnswers');
}
//end of printing function
//send form data
$('#sendAnswers').submit(function(e) {
e.preventDefault();
let formData = $(this).serialize();
console.log(formData);
// $.post({
// type: 'POST',
// url: '{{route('quizzes.store')}}',
// data: formData
// });
});
$('.saveAnswers').click(function() {
$('#sendAnswers').submit();
});
//send form data
});
}
});
});
$("#projectTable tbody tr:first-child").trigger("click");
});
</script>