Solution to the problem that setTimeout of in JS cannot call function with parameters

  • 2021-06-29 09:39:46
  • OfStack

This paper gives an example of how setTimeout() in JS can't call a function with parameters.Share it for your reference, as follows:

Solution: Override the setTimeout() method, closure functions are required.The following:


var _st = window.setTimeout;
window.setTimeout = function(fRef, mDelay){
 if (typeof fRef == 'function') {
  var argu = Array.prototype.slice.call(arguments, 2);
  var f = function(){
    fRef.apply(null, argu);
  };
  return _st(f, mDelay);
 }
 return _st(fRef, mDelay);
}

With this override, when calling a parameterized function with setTimeout(), you can use the following form:


setTimeout(fun,10,param);

fun is the by function;10 is the call cycle in milliseconds;param is a parameter to the fun function.

Another, simpler method:


function moveing(id,target_x,target_y,t){
 var ele = document.getElementById(id);
 //alert("divObject: "+ele)
 var xpos = parseInt(ele.style.left);
 //alert(ele.style.left)
 var ypos = parseInt(ele.style.top);
 if(xpos < target_x){
 xpos++;
 }
 if(ypos < target_y ){
 ypos++;
 }
 ele.style.left = xpos + "px";
 ele.style.top = ypos + "px";
// The recursively called function itself, spelled as a string, notice that 1 Quotes for parameters 
 var repeat ="moveing('"+id+"',"+target_x+","+target_y+","+t+")"; 
 var movment = setTimeout(repeat,t);
}

More readers interested in JavaScript-related content can view this site's topics: JavaScript Switching Special Effects and Techniques Summary, JavaScript Finding Algorithmic Techniques Summary, JavaScript Animation Special Effects and Techniques Summary, JavaScript Errors and Debugging Techniques Summary, JavaScript Data Structure and Algorithmic Techniques Summary,Summary of JavaScript Traversal Algorithms and Techniques and Summary of JavaScript Mathematical Operation Usage

I hope that the description in this paper will be helpful to everyone's JavaScript program design.


Related articles: