Are you doing something that requires wait until something happens to continue the code execution? need wait for a fixed or variable amount of time but the browser stills freezing ? the pooling or while method approach isn't working? thread is the solution!
If you are here maybe you have already tried some methods and different approaches, but maybe you have noticed too that if you stop your JavaScript code from execution for some time, then the browser thinks that the code has frozen, and usually show a pop-up asking if you wanna stop or continue its execution. So, how can you stop your code from execution for a fixed or even a variable time? threads are the solution, and they can be done using just the 'setTimeout' native method, without the need of any library.
Single Thread Fixed Time
Let's start with a simple thread, that executes every 1 second:
<html> <meta charset="utf-8"> <script type="text/javascript"> setTimeout(thread1, 1000); console.log('start'); function thread1() { console.log('thread1'); setTimeout(thread1, 1000); }; console.log('end'); </script> </html>
As follows, we have the function called 'thread1' that will be passed as the first parameter of the 'setTimeout' method, the second parameter is the time in milliseconds to wait before execute the function. Inside the 'thread1' we just call again the 'setTimeout' method as before, this way it will execute every 1000 miliseconds = 1 second. Below the browser's console output:
start end thread1
Single Thread Variable Time
Now let's do the same, but increasing the thread call time by 1 second, every time that it is called:
<html> <meta charset="utf-8"> <script type="text/javascript"> setTimeout(thread1, 1000); var threadTime = 1000; console.log('start'); function thread1() { console.log('thread1'+" threadTime=" + threadTime); setTimeout(thread1, threadTime); threadTime += 1000; }; console.log('end'); </script> </html>
The output:
start end thread1 threadTime=1000 thread1 threadTime=2000 thread1 threadTime=3000
Single Thread Variable Time With Event
Now let's add an event that stops our thread from running after 3 calls:
<html> <meta charset="utf-8"> <script type="text/javascript"> setTimeout(thread1, 1000); var threadTime = 1000; console.log('start'); function thread1() { console.log('thread1'+" threadTime=" + threadTime); if(threadTime < 3000) setTimeout(thread1, threadTime); else console.log('thread1 is over!'); threadTime += 1000; }; console.log('end'); </script> </html>
As we can see, no mystery, just an 'if' condition. The output:
start end thread1 threadTime=1000 thread1 threadTime=2000 thread1 threadTime=3000 thread1 is over!
Well, that's it, now you should be able to stop your code until something happens using events or just wait for a fixed/variable amount of time, this enables you to launch one or more threads too, that can execute in parallel or in sequence, as you can see here!
0 comentários :
Post a Comment