2

Is it possible to call a function with SetInterval() on specific time but execute the function only once.

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

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

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

I am expecting result to be called only once on the specify time:

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

but currently its calling two functions on 10000ms;

Maksym Semenykhin
  • 1,924
  • 15
  • 26
tonoslfx
  • 3,422
  • 15
  • 65
  • 107
  • You need to use `setTimeout` instead. – gevorg Jun 24 '16 at 12:03
  • What makes you think this is the case? – Ram Jun 24 '16 at 12:04
  • 1
    I guess, because of this `i am expecting the result to be called only one on the specify time` – gevorg Jun 24 '16 at 12:06
  • duplicate: https://stackoverflow.com/questions/20365971/timing-in-js-multiple-setintervals-running-at-once-and-starting-at-the-same-ti – mauretto Jun 24 '16 at 12:09
  • @gevorg My addressee wasn't you. I think I have misread the question anyway. I thought OP says the 2 intervals are executed at same time, i.e. the first execution of the first interval happens after 10000ms. – Ram Jun 24 '16 at 12:10

3 Answers3

5

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...

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Use setTimeout

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

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

setTimeout(function(){
  get_feed('twitter');
},10000);
Piyush.kapoor
  • 6,715
  • 1
  • 21
  • 21
  • how to call the function every 5000 or 10000ms? – tonoslfx Jun 24 '16 at 12:06
  • No, `setTimeout` executes for one time only after specified interval. Therefore your solution will just get the feed for facebook and twitter for one time only after 5 and 10 seconds respectively. – Rohit416 Jun 24 '16 at 12:15
0

Try

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

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

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

Example:

var p = document.getElementById("text");

var a = setInterval(function(){
    p.innerText = "facebook";
  }, 5000);

var a = setInterval(function(){
    p.innerText = "twitter";
  }, 10000);
<p id="text"></p>