Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Call function after 10 seconds, then each 1 minute

I have the following scenario:

I have a javascript ajax function loadCars() that needs to be called after the page loads in 10 seconds, and then every 60 seconds.

The below is what I have tried so far:

setTimeout(function(){setInterval(function(){loadCars()}, 60000)}, 10000);

What is happening is that the function is being called after 10 seconds but never again, what am I missing?

like image 834
Alex Avatar asked Jun 24 '15 14:06

Alex


People also ask

How do you call a function repeatedly every 5 seconds in JavaScript?

The setInterval() method in JavaScript can be used to perform periodic evaluation of expression or call a JavaScript function.

How do you call a function after every 5 seconds?

To call a function repeatedly after every 5 seconds in JavaScript, you can use the built-in setInterval() method. The setInterval() method calls a function repeatedly after a specified time interval. It keeps calling the function until it is explicitly stopped using the clearInterval() method.

How can we delay calling a function after 5 seconds?

To delay a function call, use setTimeout() function. functionname − The function name for the function to be executed. milliseconds − The number of milliseconds.

How do you call a function after a specific delay?

To call a jQuery function after a certain delay, use the siteTimeout() method. Here, jQuery fadeOut() function is called after some seconds.


2 Answers

You need to call loadCars on setTimeout and on setInterval.

setTimeout(function() {
    console.log('first 10 secs');
    // loadCars();
  
    setInterval(function() {
          console.log('60 secs has passed');
          // loadCars();
    }, 60000);

}, 10000);
console.log('page loaded');
like image 59
rogeriolino Avatar answered Oct 12 '22 13:10

rogeriolino


I don't agree with the answers given because they use setInterval or don't wait for the ajax call to be finished. IMO your should set a new timeout only when the function loadcars (and the ajax call) has finished.

Example:

function loadCars () {
  // ajax call happens here
  $.ajax()
    .then(function(){
      // call the function here
      setTimeout(function(){
        loadCars();
      // wait a minute after you recieved the data
      }, 60000)
    })
}

// wait 10 seconds
setTimeout(function(){
  loadCars();
}, 10000)

The advantage if this is that it will only start setting a new timeout when the HTTP request is finished and prevent the function from getting out of sync. If you use setinterval in combination with an ajax call then the next ajax call will happen in 60 seconds even if the current one is delayed for 10 seconds (and you don't want that).

like image 20
koningdavid Avatar answered Oct 12 '22 12:10

koningdavid