Home >Web Front-end >JS Tutorial >How to implement the javascript pause function
Method to implement javascript pause function: [function sleep(obj,iMinSecond){ if (window.eventList==null) window.eventList=new Array(); var...].
#The operating environment of this article: windows10 system, javascript 1.8.5, thinkpad t480 computer.
We know that javascript itself does not have a pause function (sleep cannot be used), and vbscript cannot use doEvents, so I plan to write a pause function by myself.
Tip: JavaScript is a weak object language, and a function can also be used as an object.
For example:
function Test(){ alert("hellow"); this.NextStep=function(){ alert("NextStep"); } }
We can call it like this:
var myTest=new Test();myTest.NextStep();
When we pause, we can divide a function into two parts. The code executed after the pause is placed in this.NextStep.
In order to control pause and continue, we need to write two functions to implement the pause and continue functions respectively.
The pause function is as follows:
<script language="javascript"> function sleep(obj,iMinSecond){ if (window.eventList==null) window.eventList=new Array(); var ind=-1; for (var i=0;i<window.eventList.length;i++){ if (window.eventList[i]==null) { window.eventList[i]=obj; ind=i; break; } } if (ind==-1){ ind=window.eventList.length; window.eventList[ind]=obj; } setTimeout("goon(" + ind + ")",iMinSecond); } /* 该函数把要暂停的函数放到数组window.eventList里,同时通过setTimeout来调用继续函数。 继续函数如下: */ function goon(ind){ var obj=window.eventList[ind]; window.eventList[ind]=null; if (obj.NextStep) obj.NextStep(); else obj(); } /* 该函数调用被暂停的函数的NextStep方法,如果没有这个方法则重新调用该函数。 函数编写完毕,我们可以作如下: */ function Test(){ alert("hellow"); sleep(this,3000);//调用暂停函数 this.NextStep=function(){ alert("NextStep"); } } Test(); </script>
Recommended learning: javascript video tutorial
The above is the detailed content of How to implement the javascript pause function. For more information, please follow other related articles on the PHP Chinese website!