1

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?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

I think there is a con to this... over-complication. You can do without a web worker: firing off an ajax request is something that can be done in the main thread, without the user noticing any interruption to the UI. This includes polling if you like.

The only exception to this would be if the response triggers some heavy processing in the main thread, it could hang for a moment, and the user might notice. However, processing a small response from the server, I suspect would not fall into this category.

Also: the browser can decide to kill of a web worker. To make your solution equally as robust as just an ajax call in the main thread, you would need to implement a way of recreating it. So it's even more code to write and maintain...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.