Skip to content

Instantly share code, notes, and snippets.

@imjonos
Last active January 14, 2023 15:59
Show Gist options
  • Save imjonos/5173a087926367e72749c54054642ed3 to your computer and use it in GitHub Desktop.
Save imjonos/5173a087926367e72749c54054642ed3 to your computer and use it in GitHub Desktop.
demo js worker
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test with worker</title>
<script defer src="main.js"></script>
</head>
<body>
<h1>This is the test with worker!</h1>
<div>
<label for="dataContainer">Response</label>
</div>
<textarea cols="100" rows="60" id="dataContainer"></textarea>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test without worker</title>
<script defer src="main_without_worker.js"></script>
</head>
<body>
<h1>This is the test without worker!</h1>
<div>
<label for="dataContainer">Response</label>
</div>
<textarea cols="100" rows="60" id="dataContainer"></textarea>
</body>
</html>
const url = 'https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&current_weather=true&hourly=temperature_2m,relativehumidity_2m,windspeed_10m';
const worker = new Worker('./worker.js');
worker.postMessage([url]);
worker.onmessage = (event) => {
let json = event.data;
let dataContainer = document.getElementById('dataContainer');
dataContainer.value = JSON.stringify(json);
console.log('Data', json);
}
const url = 'https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&current_weather=true&hourly=temperature_2m,relativehumidity_2m,windspeed_10m';
fetch(url).then(response =>
response.json().then(json => {
const start = (new Date()).getTime();
while ((new Date()).getTime() - start < 2 * 1000){
//some slow process
}
let dataContainer = document.getElementById('dataContainer');
dataContainer.value = JSON.stringify(json);
console.log('Data', json);
}));
addEventListener('message', event => {
const [url] = event.data;
console.log('Worker request start');
fetch(url).then(response =>
response.json().then(json => {
const start = (new Date()).getTime();
while ((new Date()).getTime() - start < 2 * 1000){
//some slow process
}
console.log('Worker request done!');
postMessage(json);
}));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment