8

我有一个循环功能,它在前 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);
        }
    );
4

2 回答 2

29

__编辑__

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

见 jsFiddle 演示

__编辑结束__

专门针对此处开放问题的旧帖子:

你可以试试:

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");
于 2013-06-12T15:47:19.360 回答
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
        });
    };
于 2017-07-31T04:39:21.320 回答