Possible duplication: JavaScript and Threads
You would want to use a worker for background tasks.
Read more: http://www.w3schools.com/html/html5_webworkers.asp
Here's an example that is related to your case:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<script id="worker1" type="javascript/worker">
self.onmessage = function(e) {
// Whatever you want to run in background, for example
for (var i = 0; i < 100; i++) {
console.log(i);
}
self.postMessage(0); // Post back a message, to close the worker
}
</script>
<script>
function run_task() {
if (typeof(Worker) != "undefined") {
// Here I am using a blob so I can run worker without using a separate file. It works on Chrome, but may not work on other browsers
var blob = new Blob([document.querySelector('#worker1').textContent], { type: "text/javascript" });
var worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = function(e) {
worker.terminate(); // Close the worker when receiving the postback message
}
worker.postMessage(1); // Start the worker. You can also use this function to pass arguments to the worker script.
} else {
// You browser does not support Worker
}
}
run_task(); // Run the function. You probably want to trigger this somewhere else
</script>
</body>
</html>
References: https://stackoverflow.com/a/6454685/2050220