tonoslfx tonoslfx - 5 months ago 20
Javascript Question

JavaScript SetInterval() Queue

Is it possible to call a function with

SetInterval()
on specific time but execute the function one the the time.

function get_feed(social) {
$.ajax({})
}

setInterval(function(){
get_feed('facebook');
},5000);

setInterval(function(){
get_feed('twitter');
},10000);


i am expecting the result to be called only one on the specify time:

on 5000ms: get_feed('facebook');
on 10000ms: get_feed('twitter');


but currently its calling two functions on 10000ms;

Answer

If I'm reading you right, you want to get feeds every five seconds and alternate between facebook and twitter. If so, use a single function:

var feed = "facebook";
setInterval(function() {
    get_feed(feed);
    feed = feed === "facebook" ? "twitter" : "facebook";
}, 5000);

currently its calling two functions on 10000ms;

That's because your original code schedules get_feed('facebook') to run every 5000ms, and get_feed('twitter') every 10000ms. So after 5000ms, it does the facebook one, then after anothr 5000ms (10000ms in total), it does both of them, then 5000ms later facebook again, then 5000ms (20000ms in total), both of them...

Comments