如何清除所有javascript超时?

时间:2013-06-12 15:43:12

标签: 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(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);
        }
    );

2 个答案:

答案 0 :(得分:28)

__ EDIT __

要管理超时(和间隔)的集合,您可以使用以下代码段。 这将允许清除代码中任何位置设置的任何超时或间隔,但是,您必须在设置任何超时或间隔之前设置此代码段。基本上,在处理任何使用超时/间隔的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]]);
        }
    }
}());

如何使用它:

像往常一样设置超时/间隔:

var test1 = setTimeout(function(){/**/, 1000);
var test2 = setTimeout(function(){/**/, 1000);

然后你可以用来清除这两个:

clearAllTimeout(); // clearAllInterval(); for intervals

这将清除两次超时(test1&amp; 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'); for namespaced intervals

这将仅清除test1超时

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

clearAllTimeout('no_ns'); // clearAllInterval('no_ns'); for non namespaced intervals only

这将在此示例中仅清除test2超时

See jsFiddle DEMO

编辑的

__ END __

此处特定于打开问题的旧帖子:

您可以尝试:

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 = [];
}

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");

答案 1 :(得分:0)

//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
        });
    };