How does javascript implement the pause function

  • 2020-10-07 18:33:04
  • OfStack

This article is an example of a custom web drag class implemented by JS. To share for your reference, the details are as follows:
Javascript itself has no pause function (sleep cannot use) and vbscript cannot use doEvents, so this function is written to realize this function.
javascript is a weak object language, and a function can also be used as an object.
Such as:


  function Test(){ 
   alert("hellow"); 
   this.NextStep=function(){ 
   alert("NextStep"); 
   } 
  } 

We can call var myTest=new Test(); myTest.NextStep();
Let's do a pause. The function is divided into two parts, the same before the pause operation, and the code to be executed after the pause is put in this.NextStep.
To control pause and continue, we need to write two functions to implement pause and continue, 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); 
  } 
  /* 
 This function puts the function to be paused into an array window.eventList In and through at the same time setTimeout To call the continuation function.  
 Continue the function as follows:  
  */ 
 
  function goon(ind){ 
   var obj=window.eventList[ind]; 
   window.eventList[ind]=null; 
   if (obj.NextStep) obj.NextStep(); 
   else obj(); 
  } 
  /* 
 This function calls the suspended function NextStep Method, if there is no such method, the function is re-called.  
   
 After the function is written, we can write as follows:  
  */ 
  function Test(){ 
   alert("hellow"); 
   sleep(this,3000);// Call pause function  
   this.NextStep=function(){ 
   alert("NextStep"); 
   } 
  } 
Test(); 
  </script>

I hope this article is helpful for you to learn javascript programming.


Related articles: