Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript timer thread

I have a function checkReg() which checks to see if my device has been registered on a server the first tine it is launched and returns a regStatus variable. The function works fine but it takes a bit of time for the reg to complete and my application cannot proceed without confirming registration is done.

I would like to use a simple thread to check the regStatus once 1 sec and after 5 tries if it hasn't been registered then kill the thread and go back, if it is done before 5 tries then kill the thread and proceed.

Thread(run every 1 sec){
    regStatus=checkReg();
    if(regStatus==='done'){

        //do something
        //kill thread
    }else if(regStatus==='inprogress'){

        //do nothing
    }elseif(regStatus==='error'){

        //kill thread
    }
}

I am quite new to JS and do not know how to start, time or kill the thread. I have used the setTimeout function but I'm not sure it can do what I want.

like image 579
Amanni Avatar asked Apr 26 '26 12:04

Amanni


1 Answers

JavaScript doesn't have threads in general, but you can easily use setInterval() instead:

var retry = 0

function checkStatus() {
  var regStatus=checkReg();
  if(regStatus==='done'){
    //...
  }
  if(++retry > 5) {
    clearTimeout(id);
  }
}

var id = setInterval(checkStatus, 1000);
like image 182
Tomasz Nurkiewicz Avatar answered Apr 29 '26 01:04

Tomasz Nurkiewicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!