Run a JavaScript function continuously repeating with a time interval

前端 未结 5 1621
南方客
南方客 2021-02-06 15:31

This is my first question, and I would appreciate you answering soon.

I would like code to repeat a function continuously... I have tried some code but it hasn\'t worked

5条回答
  •  有刺的猬
    2021-02-06 16:29

    For an Ajax-request I would use a timeout instead of an interval, and start the timeout again in the callback of the ajax-request.

    If you use an interval of say 1 second and your server takes more than one second to respond, you will start to stack calls with an interval, since the interval will call the function every second no matter what. With the timeout-in-callback approach instead, you wouldn't start the countdown until previous request has completed.

    I'm using an IIFE to trigger the first call to the function. Then when the load has completed, I use a timeout to call the function again after one second:

    (function loadContent(){
        $('#more').load('exp1.php', function () {
           setTimeout(loadContent, 1000);
        });   
    })();
    

提交回复
热议问题