Несколько запросов PHP-запросов на сбои

Я использую JQuery / PHP-скрипт, который отображает 12 часов на странице. Файл Javascript вызывает файл PHP для определения смещения временной зоны, но с 12 часами для отображения, 12 запросов PHP разбивают мою страницу.

JS FILE

/*these are the div id names you added to your html*/ var clockAllDivs = [ "clock0", "clockNYC", "clockTOR", "clockVAN", "clockLAX", "clockFRNK", "clockSAO", "clockTOK", "clockBEI", "clockHON", "clockLONDON", "clockPARIS", "clockSYDNEY" ]; var tz = jstz.determine(); // Determines the time zone of the browser client tz.name(); /*get timezone from this list: http://php.net/manual/en/timezones.php*/ var timeZones = [ tz.name(), "America/New_York", "America/Toronto", "America/Vancouver", "America/Vancouver", "Europe/Zurich", "America/Sao_Paulo", "Asia/Tokyo", "Asia/Hong_Kong", "Asia/Hong_Kong", "Europe/London", "Europe/Paris", "Australia/Sydney" ]; /*titles you want to show for each clock*/ var clockTitles = [ tz.name(), "Los Angeles", "Melbourne", "Kathmandu", "Tokyo", "Johannesburg" ]; var useTitle1 = false; var useTitle2 = false; var clockWidthHeight = 118;//width and height of the clock var distanceBetweenClockTitle = 5; var secondHandSpeed = 100;//in ms, the lower the number, the faster var smoothRotation = false;//true or false var useSecondHand = false;//set to false if you don't want to see the 2nd hand /*location of the images*/ var clockFaceImg = "img/clockBg.png"; var hourHandImg = "images/hourHand.png"; var minuteHandImg = "images/minuteHand.png"; var secondHandImg = "images/secondHand.png"; var amImg = "images/am.png"; var pmImg = "images/pm.png"; /*location of the high res images for retina display*/ var clockFaceHighResImg = "img/clockBgHighRes.png"; var hourHandHighResImg = "images/hourHandHighRes.png"; var minuteHandHighResImg = "images/minuteHandHighRes.png"; var secondHandHighResImg = "images/secondHandHighRes.png"; var amHighResImg = "images/amHighRes.png"; var pmHighResImg = "images/pmHighRes.png"; /*text for days and months*/ var dayText = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ]; var monthText = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; /////////////////////////////// //Do not edit below this line// /////////////////////////////// var clockDivs = []; var offsets = []; var minuteHand; var hourHand; var secondHands = []; var minuteHands = []; var hourHands = []; var ams = []; var pms = []; var retina = false; var imgsLoaded = 0; var imagesToLoad = 6; var callInterval = 1000; var thisOffset; var formerHr = []; var isStart = true; var tzChecked = 0; //once the page is ready . . . $( document ).ready(function() { var dNow = new Date(); thisOffset = dNow.getTimezoneOffset();//figure out user's timezone //get the timezone info for each of your clocks for(var i = 0;i<clockAllDivs.length;i++){ getTZOutput(i); } }); //build each clock function AnalogClock(){ retina = window.devicePixelRatio > 1;//check if retina //if it's high res, use the high res images if(retina){ clockFaceImg = clockFaceHighResImg; hourHandImg = hourHandHighResImg; minuteHandImg = minuteHandHighResImg; secondHandImg = secondHandHighResImg; amImg = amHighResImg; pmImg = pmHighResImg; } //determine if you want to use the second hand if(useSecondHand == false){ imagesToLoad = imagesToLoad - 1; } //change the call interval for smooth rotation if(smoothRotation == true && useSecondHand){ callInterval = 50; } //create each clock visually for(var i = 0;i<clockAllDivs.length;i++){ var clockAllDiv = $("#" + clockAllDivs[i]); //add bg clockAllDiv.append("<div id='analog-clock" + i + "' class='myClock'></div>") //add title if(useTitle1 || useTitle2){ var clockTitlePos = distanceBetweenClockTitle + clockWidthHeight; if(useTitle1)clockAllDiv.append("<div><p class='clockTitle'>" + clockTitles[i] + "</p></div>"); if(useTitle2){ clockAllDiv.append("<div><p id='title2_" + i + "' class='clockTitle2'></p></div>"); } $('.clockTitle').css({"margin-top":clockTitlePos + 'px'}); if(useTitle2 && !useTitle1)$('.clockTitle2').css({"margin-top":clockTitlePos + 'px'}); } clockDivs[i] = "analog-clock" + i; var clockDiv = $("#" + clockDivs[i]); //set clock holder css clockDiv.css({"height":clockWidthHeight + "px", "width":clockWidthHeight + "px", "position":"relative"}); //add more graphical elements clockDiv.append("<img id='bg' src=" + clockFaceImg + " height="+clockWidthHeight+" width="+clockWidthHeight+" />"); //add the div for am/pm clockDiv.append("<img id='am' class='ampm' src='" + amImg + "' width='28' height='18' />"); clockDiv.append("<img id='pm' class='ampm' src='" + pmImg + "' width='28' height='18' />"); //add hands $("<img id='hourHand' src=" + hourHandImg + " />").appendTo("#" + clockDivs[i]); clockDiv.append("<img id='minuteHand' src=" + minuteHandImg + " />"); if(useSecondHand)clockDiv.append("<img id='secondHand' src=" + secondHandImg + " />"); //define elements if(useSecondHand)secondHands[i] = $("#" + clockDivs[i] + " #secondHand"); minuteHands[i] = $("#" + clockDivs[i] + " #minuteHand"); hourHands[i] = $("#" + clockDivs[i] + " #hourHand"); ams[i] = $("#" + clockDivs[i] + " #am"); pms[i] = $("#" + clockDivs[i] + " #pm"); if(i == 0){ //check to see if the images are loaded $('#bg').load(function() { checkIfImagesLoaded(); }); if(useSecondHand)secondHands[i].load(function() { checkIfImagesLoaded(); }); minuteHands[i].load(function() { checkIfImagesLoaded(); }); hourHands[i].load(function() { checkIfImagesLoaded(); }); ams[i].load(function() { checkIfImagesLoaded(); }); pms[i].load(function() { checkIfImagesLoaded(); }); } //set clock css var handIds = $("#" + clockDivs[i] + " #bg, #hourHand, #minuteHand, #secondHand"); handIds.css({"position":"absolute"}); } }; function checkIfImagesLoaded(){ //this gets called each time an image is loaded imgsLoaded++; if(imgsLoaded == imagesToLoad){//once all the images are loaded for(var i = 0;i<clockAllDivs.length;i++){ //adjust widths and heights if 2x resolution if(retina){ if(useSecondHand)secondHands[i].css( { "height":secondHands[i].height()/2, "width":secondHands[i].width()/2 } ); minuteHands[i].css( { "height":minuteHands[i].height()/2, "width":minuteHands[i].width()/2 } ); hourHands[i].css( { "height":hourHands[i].height()/2, "width":hourHands[i].width()/2 } ); } //set the position of the hands if(useSecondHand)secondHands[i].css( { "left": (clockWidthHeight - secondHands[i].width())/2 + "px", "top": (clockWidthHeight - secondHands[i].height())/2 + "px" });//set x and y pos minuteHands[i].css( { "left": (clockWidthHeight - minuteHands[i].width())/2 + "px", "top": (clockWidthHeight - minuteHands[i].height())/2 + "px" });//set x and y pos hourHands[i].css( { "left": (clockWidthHeight - hourHands[i].width())/2 + "px", "top": (clockWidthHeight - hourHands[i].height())/2 + "px" });//set x and y pos //if(useSecondHand)setSecondStart(); //fade the clocks in $("#" + clockAllDivs[i]).animate({ opacity:1 }, "slow"); } //call rotatehands function setInterval(function(){ rotateHands(); }, callInterval);//1000 = 1 second if(!smoothRotation)rotateHands();//make sure they start in the right position } } function rotateHands(){ for(var i = 0;i<clockAllDivs.length;i++){ //get current time/date from local computer var now = new Date(); now.setMinutes(now.getMinutes() + offsets[i] + thisOffset); //set the second hand var secondAngle = 6 * now.getSeconds();//turn the time into angle if(smoothRotation)var smoothSecondAngle = now.getMilliseconds()/1000 * 6 + secondAngle; var currentHr = now.getHours(); if(formerHr[i] && currentHr != formerHr[i]){ getTZOutput(i); setDayMonthTxt(now, i); } formerHr[i] = currentHr; if(useSecondHand){ if(smoothRotation){ secondHands[i].rotate(smoothSecondAngle, 'abs');//set the hand angle }else{ if(secondAngle == 0){ secondHands[i].rotate(-6, 'abs');//set the hand angle } secondHands[i].rotate({ animateTo:secondAngle, duration:secondHandSpeed}, 'abs'); } } //set the minute hand var minuteAngle = 6 * now.getMinutes() + secondAngle/60;//turn the time into angle minuteHands[i].rotate(minuteAngle, 'abs');//set the hand angle //set the hour hand var hourAngle = 360/12 * currentHr;//turn the time into angle var hourAngleWOffset = hourAngle + minuteAngle/12; hourHands[i].rotate(hourAngleWOffset%360, 'abs');//set the hand angle } isStart = false; } //get timezone info from the function getTZOutput(thisNum) { $.ajax({ type: "POST", url:'timezone-clock-scripts/getTimezoneTime.php', data: {thisTz:timeZones[thisNum]}, dataType: "json", success: function (response) { offsets[thisNum] = response/60; allTZChecked(); }, error: function (){ console.log("error"); } }); } //make sure the php script has called first function allTZChecked(){ tzChecked++; if(tzChecked == clockAllDivs.length){ AnalogClock(); for(var i = 0;i<clockAllDivs.length;i++){ var now = new Date(); now.setMinutes(now.getMinutes() + offsets[i] + thisOffset); setDayMonthTxt(now, i); } } } function setDayMonthTxt(now, thisNum){ var thisDay = dayText[now.getDay()]; var thisMonth = monthText[now.getMonth()]; var thisDate = now.getDate(); var thisYear = now.getFullYear(); //this is what the actual strong of text looks like, but you can modify it as you please. if(useTitle2)$("#title2_" + thisNum ).html(thisDay + " " + thisMonth + " " + thisDate + ", " + thisYear); //determine am/pm if(now.getHours() < 12){ ams[thisNum].fadeIn(); pms[thisNum].fadeOut(); }else{ ams[thisNum].fadeOut(); pms[thisNum].fadeIn(); } } 

PHP FILE

 <?php $tzTxt = $_REQUEST['thisTz']; $date = new DateTime(); $tz = new DateTimeZone($tzTxt); $date->setTimezone($tz); echo $date->format(Z); //echo $date; ?> - <?php $tzTxt = $_REQUEST['thisTz']; $date = new DateTime(); $tz = new DateTimeZone($tzTxt); $date->setTimezone($tz); echo $date->format(Z); //echo $date; ?> 

Иногда страница перезагружается, иногда я получаю сообщение об ошибке «Connection Was Reset».

Когда я отключу этот скрипт, все работает нормально.

Есть ли способ изменить мои настройки PHP, чтобы этот скрипт работал, или я должен изучить другой вариант?

Если проблема в том, что ваш сервер не может обрабатывать одновременные запросы, существует несколько вариантов:

  1. Вызывайте свой php-скрипт только один раз и сразу отправляйте информацию обо всех часах. Вы можете вернуть свой скрипт json-объекту, который содержит все смещения. Это то, что я сделал бы.
  2. Вызовите функцию, когда предыдущая версия закончила (в обратном вызове или вернула обещание). Возможно, но слишком сложно, и вы поразите свой сервер еще дополнительным запросом на каждый такт.