This article describes the method of js to implement multi-threading based on setTimeout and setInterval. Share it for your reference, as follows:
JavaScript cannot implement thread blocking (sleep) because sleep involves system calls. JS does not allow system calls for security reasons.
If you have to implement the statement to continue execution, you can only use the while(1) idle method to consume the CPU, and you will break it when you judge the time. But this method is not really sleep.
Timer executed only once
<script>//The timer uses function hello(){ alert("hello");}//Execute method var t1 = window.setTimeout(hello,1000);var t2 = window.setTimeout("hello()",3000);//Execute method window.clearTimeout(t1);//Remove timer</script>Repeated execution timer
<script>function hello(){ alert("hello");}//Repeat the method var t1 = window.setInterval(hello,1000);var t2 = window.setInterval("hello()",3000);// Method to remove the timer window.clearInterval(t1);</script>question:
If two methods in a page are executed after the page is loaded, but the actual running results cannot be executed in the order you imagined, how can I solve it?
Solution:
You can add a timer to the onload method, set a timer, and then run it after "delaying" for a period of time, so that you can artificially distinguish the order of page loading and running methods.
For more information about JavaScript related content, please check out the topics of this site: "Summary of JavaScript switching effects and techniques", "Summary of JavaScript search algorithm skills", "Summary of JavaScript animation effects and techniques", "Summary of JavaScript errors and debugging techniques", "Summary of JavaScript data structures and algorithm skills", "Summary of JavaScript traversal algorithms and techniques", and "Summary of JavaScript mathematical operations usage"
I hope this article will be helpful to everyone's JavaScript programming.