使用自定义setTimeout和setInterval使之可以传递参数和对象参数_javascript技巧

WBOY
Release: 2016-05-16 18:53:49
Original
1025 people have browsed it

/******************************************************
//
// 功能: 修改window.setTimeout,使之可以传递参数和对象参数
// 使用方法: window.setTimeout(回调函数,延迟时间,参数1,参数n)
//
******************************************************/
var mySetTimeOut = setTimeout;
window.setTimeout = function(callback, timeout)
{
var args = Array.prototype.slice.call(arguments, 2);
function callFn(){callback.apply(null, args);}
return mySetTimeOut(callFn, timeout);
}
/******************************************************
//
// 功能: 修改window.setInterval,使之可以传递参数和对象参数
// 使用方法: window.setInterval(回调函数,间隔时间,参数1,参数n)
//
******************************************************/
var mySetInterval = setInterval;
window.setInterval = function(callback, interval)
{
var args = Array.prototype.slice.call(arguments, 2);
function callFn(){callback.apply(null, args);}
return mySetInterval(callFn, interval);
}
// 测试代码传递object
// 普通参数就不举例了
var obj = {height: 40px;}
var testTimeout = testInterval = null;
function test(obj)
{
alert(obj.height);
clearSetTimeOut(testTimeout);
clearInterval(testInterval);
}
var testTimeout = window.setTimeout(test, 100, obj);
var testInterval = window.setInterval(test, 100, obj);
该函数兼容ie,firefox。并且可以使用clearSetTimeOut和clearInterval清除,比原setTimeout,setInterval方便很多,并且参数可以是object。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!