如何清除所有javascript超时?

如何清除所有javascript超时?,javascript,jquery,function,settimeout,cleartimeout,Javascript,Jquery,Function,Settimeout,Cleartimeout,我有一个循环函数,它在前5秒内运行social1(),在后5秒内运行social2()然后循环 我也有2个悬停功能 我需要清除所有活动超时,因为当我将鼠标悬停在图像上(.social1&.social2)时,我可以看到多个超时正在运行 如何解决这个问题 function social1() { $('.social1').fadeTo(500, 1); $('.social2').fadeTo(500, 0.5); timeout = setTimeout(functio

我有一个循环函数,它在前5秒内运行
social1()
,在后5秒内运行
social2()
然后循环

我也有2个悬停功能

我需要清除所有活动超时,因为当我将鼠标悬停在图像上(.social1&.social2)时,我可以看到多个超时正在运行

如何解决这个问题

function social1() {
    $('.social1').fadeTo(500, 1);
    $('.social2').fadeTo(500, 0.5);
    timeout = setTimeout(function() {
          social2();
    }, 5000);
}
function social2() {
    $('.social1').fadeTo(500, 0.5);
    $('.social2').fadeTo(500, 1);
    timeout = setTimeout(function() {
          social1();
    }, 5000);
} 


$(document).ready(function ()
{
    social1();

    $('.social1').hover(
        function () {
            window.clearTimeout(timeout);
            social1();
        },
        function () {
            timeout = setTimeout(function() {
                  social2();
            }, 5000);
        }
    );
    $('.social2').hover(
        function () {
            window.clearTimeout(timeout);
            social2();
        },
        function () {
            timeout = setTimeout(function() {
                  social1();
            }, 5000);
        }
    );
__编辑__ 要管理超时(和间隔)集合,可以使用以下代码段。 这将允许清除代码中任何地方设置的任何超时或间隔,不过,您必须在设置任何超时或间隔之前设置此代码段。基本上,在处理任何使用timeout/interval的javascript代码或外部脚本之前

JS:

;(function () {
    window.timeouts = {},
    window.intervals = {},
    window.osetTimeout = window.setTimeout,
    window.osetInterval = window.setInterval,
    window.oclearTimeout = window.clearTimeout,
    window.oclearInterval = window.clearInterval,
    window.setTimeout = function () {
        var args = _parseArgs('timeouts', arguments),
            timeout = window.osetTimeout.apply(this, args.args);
        window.timeouts[args.ns].push(timeout);
        return timeout;
    },
    window.setInterval = function () {
        var args = _parseArgs('intervals', arguments),
            interval = window.osetInterval.apply(this, args.args);
        window.intervals[args.ns].push(interval);
        return interval;
    },
    window.clearTimeout = function () {
        _removeTimer('timeouts', arguments);
    },
    window.clearInterval = function () {
        _removeTimer('intervals', arguments);
    },
    window.clearAllTimeout = function () {
        _clearAllTimer('timeouts', arguments[0]);
    },
    window.clearAllInterval = function () {
        _clearAllTimer('intervals', arguments[0]);
    };

    function _parseArgs(type, args) {
        var ns = typeof args[0] === "function" ? "no_ns" : args[0];
        if (ns !== "no_ns")[].splice.call(args, 0, 1);
        if (!window[type][ns]) window[type][ns] = [];
        return {
            ns: ns,
            args: args
        };
    }

    function _removeTimer(type, args) {
        var fnToCall = type === "timeouts" ? "oclearTimeout" : "oclearInterval",
            timerId = args[0];
        window[fnToCall].apply(this, args);
        for (var k in window[type]) {
            for (var i = 0, z = window[type][k].length; i < z; i++) {
                if (window[type][k][i] === timerId) {
                    window[type][k].splice(i, 1);
                    if (!window[type][k].length) delete window[type][k];
                    return;                        
                }
            }
        }
    }

    function _clearAllTimer(type, ns) {
        var timersToClear = ns ? window[type][ns] : (function () {
            var timers = [];
            for (var k in window[type]) {
                timers = timers.concat(window[type][k]);
            }
            return timers;
        }());
        for (var i = 0, z = timersToClear.length; i < z; i++) {
            _removeTimer(type, [timersToClear[i]]);
        }
    }
}());
然后您可以使用清除这两个选项:

clearAllTimeout(); // clearAllInterval(); for intervals
这将清除两个超时(
test1
test2

您可以使用某些名称空间仅清除特定计时器,例如:

// first (optional) parameter for setTimeout/setInterval is namespace
var test1 = setTimeout('myNamespace', function(){/**/, 1000); // 'myNamespace' is current namespace used for test1 timeout
var test2 = setTimeout(function(){/**/, 1000); // no namespace used for test2 timeout
同样,
clearAllTimeout()将清除两个超时。要仅清除带名称空间的,可以使用:

clearAllTimeout('myNamespace');//clearAllInterval('myNamespace');对于命名空间间隔

这将仅清除
test1
超时

出于某种原因,您可能只希望删除非命名空间超时。然后,您可以使用:

clearAllTimeout('no_ns');//clearAllInterval(“无”);仅适用于非名称空间间隔

在本例中,这将仅清除
test2
timeout

__编辑结束__ 关于开场白问题的旧帖子如下: 你可以试试:

var超时=[];
timeouts.push(setTimeout(函数()){
社会2();
}, 5000));
timeouts.push(setTimeout(函数()){
社会1();
}, 5000));
//等等。。。
函数clearAllTimeouts(){
对于(变量i=0,z=timeouts.length;i
在David Thomas评论后更新

var timeouts = {'social' : [], 'antisocial' : []};

//a social timeout
timeouts.social.push(setTimeout(function() {
              social1();
        }, 5000));

//an anti-social timeout
timeouts.antisocial.push(setTimeout(function() {
              antisocial1();
        }, 5000));

function clearTimeouts(namespace){
       for(var i = 0, z = timeouts[namespace].length; i < z; i++)
           clearTimeout(timeouts[namespace][i]);

       timeouts[namespace] = [];
    }

//usage e.g
clearTimeouts("social");
var超时={'social':[],'antissocial':[]};
//社交暂停
timeouts.social.push(setTimeout(function()){
社会1();
}, 5000));
//反社会的暂停
timeouts.antisocial.push(setTimeout(function()函数){
反社会的1();
}, 5000));
函数清除超时(命名空间){
对于(var i=0,z=timeout[namespace].length;i
//如果您正在寻找完整的代码
var dict={};
函数检查间隔(id){
var指数=指数;
var result=findoradproperty(id);
如果(result.length!=0){
净空时间(id);
}
dict[id].push(setTimeout(function(){alertFunc(id,index);},60000));
};
//清除特定区域超时
函数clearTimeoutsFor(命名空间){
for(var i=0,z=dict[namespace].length;i
setTimeout
不是jQuery。如果需要清除多个,则需要手动管理它们的集合。如何手动管理它们?将变量(包含名称/引用)推送到数组中,然后迭代该数组并调用
clearTimeout()
。如@DavidThomas所建议,使用JavaScript中提供的基本集合类型(对象或数组)。或者只使用两个不同的变量,
timeout1
timeout2
。但是数组的通用性更好。您可以显示一个伪名称,用空格隔开表示
timeouts={'social':[],'antisocial':[]}
并且在
clearalltimouts()
函数中接受一个特定的键?(你已经获得了6张(应得的)选票,所以这不一定值得,但既然你已经开始……)当这看起来像某种切换,而不是需要推广到很多元素时,这似乎有点过头了。如果真的只有这两个元素,那么我会同意@Barmar。此外,这个答案甚至不需要清除数组,这意味着它会越来越长。人们真的应该更加小心投票。顺便说一句,我从这个答案中只赢了2分:)不管怎样,thx大卫和疯狂永远训练inputs@DavidThomas,烤熟了:说清楚点,我在获得一个答案方面没有问题。在国际海事组织,这是一个相当严重的疏忽,特别是对于悬停事件,但它现在已经修复,所以不再是一个问题。这就是我第一次评论中真正想要的内容。:-)请在答案中添加描述
var timeouts = [];

timeouts.push(setTimeout(function() {
          social2();
    }, 5000));

timeouts.push(setTimeout(function() {
          social1();
    }, 5000));

//etc...

function clearAllTimeouts(){
   for(var i = 0, z = timeouts.length; i < z; i++)
       clearTimeout(timeouts[i]);

   timeouts = [];
}
var timeouts = {'social' : [], 'antisocial' : []};

//a social timeout
timeouts.social.push(setTimeout(function() {
              social1();
        }, 5000));

//an anti-social timeout
timeouts.antisocial.push(setTimeout(function() {
              antisocial1();
        }, 5000));

function clearTimeouts(namespace){
       for(var i = 0, z = timeouts[namespace].length; i < z; i++)
           clearTimeout(timeouts[namespace][i]);

       timeouts[namespace] = [];
    }

//usage e.g
clearTimeouts("social");
//Incase if you are looking for full fledged code
    var dict = {};
    function checkForIntervals(id){
        var index = index; 
        var result = findOrAddProperty(id);
        if(result.length != 0){
             clearTimeoutsFor(id);
         }
         dict[id].push(setTimeout(function(){alertFunc(id,index);}, 60000)); 
    };

    // to clear specific area timeout
    function clearTimeoutsFor(namespace){
        for(var i = 0, z = dict[namespace].length; i < z; i++)
            clearTimeout(dict[namespace][i]);

        dict[namespace] = [];
    }

    to clear all timeouts
    function clearAllTimeOuts(){
        for (key in dict) {
            for(var i = 0, z = dict[key].length; i < z; i++)
                clearTimeout(dict[key][i]);
            dict[key] =[];
         }
    };

    function findOrAddProperty(str){
        var temp  = [];
        for (key in dict) {
              if(key == str){
                  if (dict.hasOwnProperty(key)) {
                        temp = dict[key];
                        break;
                      }
              }
         }
        if(temp.length == 0){
            dict[str] = [];
        }
        return temp;
    };


    function alertFunc(id,index) {
        jQuery(document).ready(function($) {
            do the ajax call here after 1 min
        });
    };