This time I will bring you how to suspend the execution of js and what are the precautions for suspending the execution of js. The following is a practical case, let's take a look.
JavaScript is a single-threaded scripting language that can handle asynchronous tasks. It does not provide sleep and other similar methods. When there is a need to pause the js script, you can use the following Method Single-thread analysis
1: Alert and comfirm pop-up windows are paused
js’s alert and confirm pop-up window class methods can pause the execution of js scripts
For example:
<script> console.log(1); alert(1); console.log(2); </script>
## In this pop-up window, you need to click to confirm to execute the following statement
Even the timer is paused<script> var i=0; setInterval(function(){ console.log(i); i++; if(i==5){ alert(i); } },500) </script>
So, if you need to pause, you can use the pop-up method to pause the script. The disadvantage is that it will affect the user experience.
2: while(); method to pause. The while method can pause, However, it will affect the performance of the browser and is difficult to control<script> var i=0; console.log(new Date()); while(i<5000000000){ i++; } console.log(new Date()); </script>
Three, ajax synchronization
Request methodThis method requires server cooperation to be implemented. I don’t recommend it because I am too lazy to test it.Probably The steps are: Ajax requests the server synchronously, with a parameter time. After the server receives it, sleep(time), output again at the time, and return to ajax
Callback function. During this time, ajax is stopped.
Finally, I would like to add a few words. In fact, js cannot pause the script. The above method only preempts the current browser thread, which is equivalent to a certain statement of the thread still staying in the current browser thread.For example: while, the current execution has not been completed
while loopThis method, so the thread cannot exit
Does not allow switching execution, so a pause is implemented I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
How to use JQ to right-click to collect web pagesaja’s asynchronous upload plug-in
jQuery implements form validation after multi-layer validation
The above is the detailed content of How to make js pause execution. For more information, please follow other related articles on the PHP Chinese website!