JS学习-setTimeout()
setTimeout()
超时限制-节流
/* interval(),在setInterval()时间间隔到期后调用。
* timeout()setTimeout()计时器到期后调用。
* run(),在程序启动时调用。
* logline()在间隔和计时器到期时称为,它在出现节流时显示最近的间隔和当前的间隔以及指示符。
**/
var to_timer = 0; // duration is zero milliseconds
var interval_timer = 0; // expires immediately
var cleanup_timer = 0; // fires at end of run
var last = 0; // last millisecond recorded
var duration = 15; // run duration in milliseconds
var lineno = 0; // current output line number
function interval() {
logline(new Date().getMilliseconds());
}
function timeout() {
logline(new Date().getMilliseconds());
interval();
to_timer = setTimeout(timeout, 0);
}
function run() {
interval_timer = setInterval(interval, 0);
to_timer = setTimeout(timeout, 0);
cleanup_timer = setInterval(cleanup, duration);
last = 0;
lineno = 0;
document.getElementById("log").innerHTML = "";
document.getElementById("log").innerHTML = "line last current";
}
function logline(msec) {
// msec can't wrap: run duration > 1 second
var c = "";
if ((last != 0) && (last > msec - 1 /* variation */)) {
c = "Throttled";
}
document.getElementById("log").innerHTML += "<pre>" + pad(lineno++, 2) + " " + pad(last, 3) + " " + msec + " " + c;
last = msec;
}
function cleanup() {
clearTimeout(to_timer);
clearInterval(interval_timer)
}
function pad(num, count) {
return num.toString().padStart(count, '0')
}
<p>Live Example</p>
<button onclick="run();">Run</button>
<div id="log"></div>
polyfill
将一个或多个参数传递给回调函数,但又在不支持使用setTimeout()或setInterval()(例如Internet Explorer 9及以下版本)发送其他参数的浏览器中运行,则 可以添加此polyfill来启用HTML5标准参数传递功能。
/*\
|*|
|*| 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[, arg1, arg2, ...]);
|*| var timeoutID = window.setTimeout(code, delay);
|*| var intervalID = window.setInterval(func, delay[, arg1, arg2, ...]);
|*| 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');
}())
兼容IE9
- js页面注释
/*@cc_on
// conditional IE < 9 only fix
@if (@_jscript_version <= 9)
(function(f){
window.setTimeout = f(window.setTimeout);
window.setInterval = f(window.setInterval);
})(function(f){
return function(c,t){
var a=[].slice.call(arguments,2);
return f(function(){
c instanceof Function ? c.apply(this,a) : eval(c)
},t)
}
});
@end
@*/
- html页面注释
<!--[if lte IE 9]>
<script>
(function(f){
window.setTimeout=f(window.setTimeout);
window.setInterval=f(window.setInterval);
})(function(f){
return function(c,t){
var a=[].slice.call(arguments,2);
return f(function(){
c instanceof Function ? c.apply(this,a) : eval(c)
},t)
}
});
</script>
<![endif]-->
this指向
当您将方法传递给setTimeout()(或其他任何函数)时,将使用this可能与您期望的值不同的值来调用该方法。
myArray = ['zero', 'one', 'two'];
myArray.myMethod = function (sProperty) {
console.log(arguments.length > 0 ? this[sProperty] : this);
};
setTimeout(myArray.myMethod, 1.0*1000); // [object Window]
setTimeout(myArray.myMethod, 1.5*1000, '1');
// ERR:Blocked a frame with origin "https://developer.mozilla.org" from accessing a cross-origin frame. at myArray.myMethod
- 匿名函数
setTimeout(function(){
myArray.myMethod('1')
}, 2.5*1000);
- 箭头函数
setTimeout(() => {
myArray.myMethod('1')
}, 2.5*1000);
- bind
setTimeout(myArray.myMethod.bind(myArray), 1.5*1000, '1');
timeOut延时
// 直到调用的线程setTimeout()终止,函数或代码段才能执行
function foo() {
console.log('foo has been called');
}
setTimeout(foo, 0);
console.log('After setTimeout');
After setTimeout
foo has been called
最大timeOut值
包括Internet Explorer,Chrome,Safari和Firefox在内的浏览器在内部将延迟存储为32位带符号整数。当使用大于2,147,483,647 ms(约24.8天)的延迟时,这会导致整数溢出,从而导致超时立即执行。