Run a JavaScript function continuously repeating with a time interval

前端 未结 5 1624
南方客
南方客 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:14

    you can do this like

    var myFunction = function() {
        $('#more').load('bla.php'); 
    };
    
    var timer =  setInterval(myFunction, 1000); // call every 1000 milliseconds
    

    or

    var timer = setTimeout(myFunction, 1000); // call every 1000 milliseconds
    
    clearTimeout(timer); //To stop the function from being called forever
    

    as @Christofer Eliasson For an Ajax-request, you would probably want to use a timeout instead of an interval, an start the timeout again in the callback, to make sure that you don't stack calls if the server is taking more than 1 second to respond

    Good Read

    1. MDN:window.setTimeout
    2. MDN:window.setInterval

提交回复
热议问题