如何在随机生成的函数中清除间隔

时间:2013-09-23 21:04:44

标签: javascript jquery

我定义了几个函数。 setInterval每秒随机选取一个。如何暂时清除间隔以暂停此行为?

演示: http://jsfiddle.net/kthornbloom/NtVBZ/1/

代码:     function playZoomout(){         $(”。调试 ')附加(' 1' )。     }

function playZoomin() {
    $('.debug').append('2');
}

function playPanright() {
    $('.debug').append('3');
}

function playPanleft() {
    $('.debug').append('4');
}

var fns = [playZoomout, playZoomin, playPanright, playPanleft]
setInterval(function () {
    fns[Math.floor(Math.random() * fns.length)]();
}, 1000);

// This isn't working. Probably because the interval above isn't really named?
$('.pause').hover(function(ev){
    clearInterval(fns);
}, function(ev){
    timer = setInterval( fns, 1000);
});

1 个答案:

答案 0 :(得分:2)

var fns = [playZoomout, playZoomin, playPanright, playPanleft];
var fn = function () {
    fns[Math.floor(Math.random() * fns.length)]();
}

var myInterval = setInterval(fn, 1000);

$('.pause').hover(function(ev){
    clearInterval(myInterval);
}, function(ev){
    //timer = setInterval( fns, 1000); -> this does not make sense
    myInterval = setInterval(fn, 1000); // this does
});

Working demo