Home > Article > Web Front-end > How to implement pause in loop with jQuery and JS_javascript skills
The example in this article describes how jQuery and JS implement pause in the loop. Share it with everyone for your reference. The specific analysis is as follows:
Question:
jquery loops the array. If you require a pause of 2 seconds each time it loops, when using jQuery's .earch loop, no matter how you set it, it will not pause.
setTimeout also only pauses the first time it is executed.
Cause guess:
js starts executing multi-threading?
Improvements:
Change to setInterval to control the loop. When the maximum value of the array is reached, clearInterval cancels the loop.
The following is the jQuery code:
<script type="text/javascript"> var arr = new Array(); var arrk = 0; jQuery(function() { arr[0] = "aaa.keleyi.com"; arr[1] = "bbb.keleyi.com"; arr[2] = "ccc.keleyi.com"; mytime = setInterval(function(){showme()}, 2000); function showme(){ alert(arr[arrk]); arrk += 1; if(arrk>2) clearInterval(mytime); } }); </script>
The following is the Javascript code:
<script type="text/javascript"> var arr = new Array(); var arrk = 0; arr[0] = "aaa.keleyi.com"; arr[1] = "bbb.keleyi.com"; arr[2] = "ccc.keleyi.com"; mytime = setInterval(function () { showme() }, 2000); function showme() { alert(arr[arrk]); arrk += 1; if (arrk > 2) clearInterval(mytime); } </script>
I hope this article will be helpful to everyone’s JavaScript programming design.