javascript - How to make function run once inside setInterval -


hi friends have trouble while doing ..

     getsocketpersecond = function () {             interval_persecond = setinterval(function () {               $.ajax({                 url: "/asset/ashx/getsocket.ashx",                 type: "post",                 success: function (data) {                 switch (status) {                     case "opendoor":                                              opendoor();                         break                     case "closedoor":                      closedoor();                         break                                  }             }, error: function () { }         })     }, 500) }  function opendoor(){ console.log('open door');}  function closedoor(){ console.log('close door');} 

the console log coming

ajax request // opendoor string open door ajax request open door ajax request open door ajax request // closedoor string close door ajax request close door ajax request close door 

i wish console

 ajax request open door  ajax request  ajax request  ajax request  ajax request close door  ajax request  ajax request  ajax request  ajax request 

i tried make no idea function run once since ajax in repeat, need . thousand of thank .

you need keep track of last status has been handled can tell when changes:

getsocketpersecond = function () {     var laststatus;      interval_persecond = setinterval(function () {         $.ajax({             url: "/asset/ashx/getsocket.ashx",             type: "post",             success: function (data) {                 if (laststatus === status) {                     return;                 }                  laststatus = status;                  switch (status) {                     case "opendoor":                                                 opendoor();                     break                     case "closedoor":                         closedoor();                     break                                  }             },             error: function () { }         })     }, 500) }  function opendoor() {     console.log('open door'); }  function closedoor() {     console.log('close door'); } 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -