This article analyzes the solution to the problem that setTimeout() cannot call the parameter function in JS. Share it for your reference, as follows:
Solution: Rewrite the setTimeout() method and use the closure function. as follows:
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 such rewriting, when using setTimeout() to call the parameter function, you can use the following form:
setTimeout(fun,10,param);
where fun is the function; 10 is the call cycle, the unit is milliseconds; param is the parameter of the fun function.
Another simpler way:
function moving(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 function itself is called recursively, spelled into a string form, pay attention to the quotes of the first parameter var repeat ="moveing('"+id+"',"+target_x+","+target_y+","+t+")"; var movment = setTimeout(repeat,t);}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.