setTimeout
第一个参数可选函数或字符串,但是字符串的方式设计到eval()函数的安全风险,所以不建议使用。
var timeoutId = window.setTimeout(function(){alert(1)} , 1000);
var timeoutId = window.setTimeout("alert(1)" , 1000);
//设置点击,同时避免一次执行内多次点击
var alarm = {
remind: function(aMessage) {
alert(aMessage);
this.timeoutID = undefined;
},
setup: function() {
if (typeof this.timeoutID === 'number') {
this.cancel();
}
this.timeoutID = window.setTimeout(function(msg) {
this.remind(msg);
}.bind(this), 1000, 'Wake up!');
},
cancel: function() {
window.clearTimeout(this.timeoutID);
this.timeoutID = undefined;
}
};
window.onclick = function() { alarm.setup(); };
polyfill 腻子
如果浏览器不支持传递参数的话使用
/*\
|*|
|*| Polyfill which enables the passage of arbitrary arguments to the
|*| callback functions of JavaScript timers (HTML5 standard syntax).
|*|
|*| https://developer.mozilla.org/en-US/docs/DOM/window.setInterval
|*|
|*| Syntax:
|*| var timeoutID = window.setTimeout(func, delay[, param1, param2, ...]);
|*| var timeoutID = window.setTimeout(code, delay);
|*| var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
|*| var intervalID = window.setInterval(code, delay);
|*|
\*/
(function() {
setTimeout(function(arg1) {
if (arg1 === 'test') {
// feature test is passed, no need for polyfill
return;
}
var __nativeST__ = window.setTimeout;
window.setTimeout = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */ ) {
var aArgs = Array.prototype.slice.call(arguments, 2);
return __nativeST__(vCallback instanceof Function ? function() {
vCallback.apply(null, aArgs);
} : vCallback, nDelay);
};
}, 0, 'test');
var interval = setInterval(function(arg1) {
clearInterval(interval);
if (arg1 === 'test') {
// feature test is passed, no need for polyfill
return;
}
var __nativeSI__ = window.setInterval;
window.setInterval = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */ ) {
var aArgs = Array.prototype.slice.call(arguments, 2);
return __nativeSI__(vCallback instanceof Function ? function() {
vCallback.apply(null, aArgs);
} : vCallback, nDelay);
};
}, 0, 'test');
}())