Search code examples
setintervalweb-worker

using setinterval function in html5 web worker to poll server


I have an e-mail button in my page, which shows how many unread messages user has. There is an endpoint that returns the number of unread messages.

I want the numbers of messages to be refreshed without having user to refresh the whole page.

I'm thinking of using setInterval in html5 web worker to call the endpoint each 10 seconds maybe and update ui accordingly if there are new messages.

What are the cons of such approach? If there is a better way to implement such thing?


Solution

  • I don't see any "con" to this approach. It will run in a different thread so your mainJS won't be interrupted. Make sure to implement correct error handling though! You want to close the worker if something unexpected happens.

    Here is an example of a webworker JS file where I did something similar:

    function checkStatus() {
        var ajaxRequest = new XMLHttpRequest();
        ajaxRequest.onreadystatechange = function() {
            if(ajaxRequest.readyState == 4) {
                self.postMessage(ajaxRequest.responseText);
                var timer;
                timer = self.setTimeout(function(){
                    checkStatus();
                }, 10000); // 10 seconds
            }
        }
    
        var queryString = "?"; // hand over i.e. a userID
        ajaxRequest.open("GET", "/statusCheck.php"+queryString, true);
        ajaxRequest.send(null);
    }
    
    this.onmessage  =   function(e){
        checkStatus();
    };
    

    This is very simplified. The message from my mainJS contains for example the userID and other variables so you can hand them through all the way to your statusCheck.php as GET or POST arguments. I'd recommend using a JSON formatted string as response from your php where you'd also have the number of mails for your user. self.postMessage()hands that back to your mainJS and you can do with it whatever you like. :)