Web Worker là một trong những tính năng mới rất đáng giá của HTML5, với nó các nhà phát triển, lập trình ứng dụng web có thể làm được các chuyện sau:
- Xử lí tệp tin với HTML5 và JavaScript
- JavaScript và Cache trong HTML5
Ngoài ra bạn có thể xem thêm nhiều tính năng khác có trên HTML5 cùng với web worker tại Các hàm JavaScript mới trong HTML5, nhưng hôm nay, jsB@nk muốn giới thiệu với bạn thêm một ứng dụng khác của Web Worker, đó là tạo ra các ứng dụng JavaScript có thể xử lý đa luồng. Bạn vui lòng vào trang chi tiết để xem hướng dẫn đầy đủ.
- Demo
- Phóng to
- Tải lại
- Cửa sổ mới
Tạo video bằng AI chỉ với giọng nói hoặc văn bản
Ứng dụng video AI MIỄN PHÍ hàng đầu của bạn! Tự động hóa video AI đầu tiên của bạn. Tạo Video Chuyên Nghiệp Của Bạn Trong 5 Phút Bằng AI Không Cần Thiết Bị Hoặc Kỹ Năng Chỉnh Sửa Video. Sản xuất video dễ dàng dành cho nhà tiếp thị nội dung.
Web Workers defines an API that can be used for
running scripts in background threads. In traditional browsers
javascript was capable of running in a single thread, due to which it
was difficult to run background tasks. Also the capabilities and
performance of client side applications were limited. However, there are
some asynchronous functions like "setTimeout" and "setInterval" which
provide nice work around for running background tasks.
I have divided this blog into two parts. First one explains the single
threaded model of traditional browsers and the second one explains how
to use Web Workers. You can skip the first section, if you have good hold on javascript.
Single Threaded Model
The way javascript handles various asynchronous ajax calls or various
timer functions, it makes us feel that javascript runs in multiple
threads. Now, how does browser handle the UI events when it is executing
a particular block of code, or how does browser handle the asynchronous
timer and ajax calls when it just has a single thread for execution.
The answer to all these questions lies in the way browser queues up
various functions for execution.
Let us take an example of the following script
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <script type= "text/javascript" > function init(){ takes 5 ms to be executed mouseClickEvent occurs takes 5 ms setInterval(timerTask, "10" ); takes 5 ms } function handleMouseClick(){ takes 8 ms to be executed } function timerTask(){ takes 2 ms to be executed } </script> |
Figure below shows the execution of the above script. Please pay
extra attention to this figure as it contains a lot of information
Let us say that at 0 ms init() function starts executing and during the execution of init() function, a mouse click event occurs at 5ms. Now, as the main thread is already executing the init() function and is capable of executing just a single block of code at a time, it queues up handleMouseClick() function next in the execution queue. At 10 ms init()
function sets a timer which will execute every 10 ms. Fist execution of
the timer task is scheduled at 20 ms, second at 30 ms and so on. The
execution of init() function takes 15 ms and after its completion, handleMouseClick() being next in the queue starts executing i.e. starts executing at 15ms. Execution of handleMouseClick() function takes 8 ms i.e. it completes at 23 ms and as timerTask() function was scheduled to run at 20ms, timerTask() function gets queued up in execution queue and is executed after the handleMouseClick() completes. Since there is no other function present in the execution queue that need to be run, timerTask() function runs at its scheduled time i.e. 30 ms , 40 ms and so on.
Web Workers
Web Workers allows you to load your script dynamically and run
it in background thread. Creating a worker is simple. All you have to do
is, call the constructor and pass the URI of the script you want to
execute as an argument. Workers are relatively heavy weight and are not
intended to be used in large number.
1 2 | // Creates a Web Worker var worker = new Worker( "worker.js" ); |
Workers don't have access to the DOM i.e. you don't have direct access to the 'parent' page. However, Web Workers API do provide you with methods like "onmessage" and "postmessage" which let you communicate with the main thread.
- onmessage : method used for receiving messages sent from the worker, also can be used in worker for receiving messages sent from main thread.
- postmessage : method used for sending messages from worker to the main thread, also can be used in main thread for sending messages to worker.
Lets take an example and see how exactly these methods can be used for communicating through messages
Here is the main script that created a new worker. In worker's onmessage event handler, we log all the messages received from the worker, i.e. this event handler is called when postmessage() function is called from the worker. This script also sets a timer, which calls the sendMsgToWorker() function every 5 sec.
1 2 3 4 5 6 7 8 9 10 11 | <script type= "text/javascript" > var worker = new Worker( 'worker.js' ); worker.onmessage = function (e){ console.log(e.data); } function sendMsgToWorker(){ worker.postMessage( " Sent Message From main " ); } setInterval(sendMsgToWorker, "5000" ); </script> |
Lets have a look at "worker.js" script.
1 2 3 4 5 6 7 8 9 | onmessage = function (event) { var message = " In worker on message method :" + event.data; postMessage(message); }; function sendMsgToMain(){ postMessage( " Sent Message From worker" ); } // Call sendMsgToMain method again after 5seconds setInterval(sendMsgToMain, "5000" ); |
When we load the page containing the main script, the logs shown on the browser console are as follows
1 2 3 4 5 6 7 | In worker on message method : Sent Message From main Sent Message From worker In worker on message method : Sent Message From main Sent Message From worker In worker on message method : Sent Message From main Sent Message From worker ............ |
In this example, the main thread starts a new thread and instantiates a timer which calls sendMsgToWorker() function every 5 seconds. sendMsgToWorker() function sends a message i.e. "Sent Message From main" to worker by calling postmessage function on worker object. The worker receives this message in the onmessage callback function(in "worker.js" script) which prefixes the message with "In worker on message method :" and sends it back to the main thread using postMessage() function of worker API. Also, worker thread instantiates a timer which calls sendMsgToMain() function every 5 seconds. sendMsgToMain() sends a message i.e. "Sent Message From worker" to the main thread using postmessage() function. Messages sent by calling postmessage in 'worker.js' are received by worker.onmessage callback function(in main script) and are then logged to the console.
So, now there are two threads that run forever. First one is the main thread that receives messages sent from worker and logs them to the console and also sends a message every 5 seconds to the worker. Second thread, is the worker thread which sends the received messages from the main thread, back to the main thread and also sends a message every 5 seconds.
At last I would like to mention the objects and functions that can be used inside worker
Functions that can be called from Web Workers are
- importScripts(): used to load external Javascript for use in the worker
- setTimeout() and setInterval(): used for setting timer tasks
- close(): stops the worker immediately
Objects that are available in Web Workers are
- navigator
- location
- All javascript objects, like Array, Date, etc
- XMLHttpRequest
- Lượt gửi (0)
- Mới
Tạo video doanh nghiệp của bạn bằng AI chỉ với giọng nói hoặc văn bản
chatGPTaz.com
Nói chuyện với ChatGPT bằng ngôn ngữ mẹ đẻ của bạn
Ứng dụng AI Video
Ứng dụng video AI MIỄN PHÍ đầu tiên của bạn
Deepfake Video
Deepfake AI Video Maker
Deepfake
Deepfake AI Video Maker
AI Deep Fake
Deepfake AI Video Maker
AIvidio
AI Video Mobile Solutions
AIvideos
AI Video Platform & Solutions
AIvedio
AI Video App Maker
Artificial General Intelligence
Ai and higher level Artificial General Intelligence (AGI)
Artificial General Intelligence
Ai and higher level Artificial General Intelligence (AGI)
Faceswap AI trực tuyến
Đổi mặt Video, Ảnh & GIF ngay lập tức với Công cụ AI mạnh mẽ - Faceswap AI Trực tuyến MIỄN PHÍ
Faceswap AI trực tuyến
Đổi mặt Video, Ảnh & GIF ngay lập tức với Công cụ AI mạnh mẽ - Faceswap AI Trực tuyến MIỄN PHÍ
Faceswap AI trực tuyến
Đổi mặt Video, Ảnh & GIF ngay lập tức với Công cụ AI mạnh mẽ - Faceswap AI Trực tuyến MIỄN PHÍ
Powerful AI Presentation PPT Maker for FREE
Build an impressive presentation with our free online AI presentation app
Your next top AI Assistant
Claude AI, developed by Anthropic
Your next top AI Assistant
Claude AI, developed by Anthropic
Temu tặng $500 cho người dùng mới
Claim Free Temu $500 Credit via Affiliate & Influencer Program
Tín dụng quảng cáo TikTok miễn phí
Làm chủ quảng cáo TikTok cho hoạt động tiếp thị doanh nghiệp của bạn
Dall-E-OpenAI.com
Tự động tạo ra hình ảnh sáng tạo với AI
chatGPT4.win
Nói chuyện với ChatGPT bằng ngôn ngữ mẹ đẻ của bạn
Sản phẩm AI đầu tiên của Elon Musk - Grok/UN.com
Nói chuyện với Grok AI Chatbot bằng ngôn ngữ của bạn
Công cụ.win
Mở trung tâm công cụ miễn phí để mọi người sử dụng với hàng trăm công cụ
GateIO.gomymobi.com
Airdrop miễn phí để nhận, chia sẻ lên đến 150.000 đô la cho mỗi dự án
iPhoneKer.com
Tiết kiệm tới 630$ khi mua iPhone 16 mới
Mua Robot Tesla Optimus
Đặt mua Tesla Bot: Robot Optimus Gen 2 ngay hôm nay với giá dưới 20.000 đô la