简体   繁体   中英

ERR_INSUFFICIENT_RESOURCES ajax code for REAL-TIME CLOCK

I created a real-time clock that updates every second. When I run it locally I see no errors. However when I uploaded it to my web host I saw a lot of error messages in the console every time the AJAX code runs.

I think that's the reason why web host suspended my site, telling that my site has performed too many requests.

Here is my code:

$(document).ready(function() {  
  setInterval(function() {
    $('#time').load('timewithdate.php')
  }, 1000);

  setInterval(function(){
    $('#time2').load('time.php')
   }, 1000);
})

The error is because you have effectively DDOS'd your own server with 2 requests every second * number of concurrent clients. I would strongly suggest you remove these AJAX requests and perform the countdown on the client side.

If you're trying to keep the clocks in sync with server time, get the time from the server when the page loads, then add seconds to it on the client side. Do not use AJAX for this, and do not use AJAX polling in future. It's an anti-pattern.

I'm not sure what kind of answer you are looking for. Your code is a certain way to kill a server: it's making 2 calls to the server every second for each client (read more aboutDDOS ). There is no need to make a server call, just use javascript to get the current time and format it the way you want. You can have something like this:

$(document).ready(function() {  
  setInterval(function() {
    let curTime = new Date();
    let date = curTime.toLocaleDateString();
    let time = curTime.toLocaleTimeString();
    $('#time').text(date + " " + time);
    $('#time2').text(time);
  }, 1000);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM