简体   繁体   中英

why setinterval slows down the website

I am using this simple function but it much skows down the web site depending on the time the webpage has been opened.when user refresh or goes to another page,it takes much time to refresh.

I am basically fecthing the user new posts.so time must keep running.

If i dont use this function then webpage loads quickly.Although this is a simple function Plz help or suggest any alternarive approach.

$(document).ready(function() {
   setInterval( "timer();", 1000 );
});

function timer(){
    $.post('sendchat2.php', {option:'timer',id= $('#timer').val()}, function(data) {
        $('#timer').html(data);

    })
}

This is how I'd do it:

$(function () {

    var $timer = $ ( '#timer' );

    (function timeout () {
        $.post( 'sendchat2.php', { option: 'timer', id = $timer.val() }, function ( data ) {
            $timer.html( data );
            setTimeout( timeout, 1000 );  
        });            
    }());

});

So, you initiate the Ajax-request, wait for the response, inject it into the DOM, and only then initiate a one second timeout which repeats the whole process.


The general pattern:

(function f () {

    async(function () {

        // do work here

        setTimeout( f, delay );

    });

}());

So, the function f executes some asynchronous operation (eg Ajax request). The callback function of that operation performs some work (eg put Ajax response into DOM), and at the end it sets up a timer which invokes the f function after a given delay.

The slowdown is not because of the setInterval() , you are calling that function "timer" every 1 second with setInterval, that should slow the page down only 1000 (1 second).

The problem is in the $.post() , which is an Ajax request, what that exactly do is, send some information to the script (php), php then processes the information resulting in some output, then this output is sent again to the first page, and the $.post() writes this information in your $('#timer') element.

So probably the slowdown is because of :

  • The php script is where the delay is being generated
  • The data returned from sendchat2.php is very big, therefore delaying the pageload.

Also, sending an ajax request every second is not very healthy, the php script could be being overloaded. You might want to google for push methods or polling methods to develop the chat correctly

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