2017-07-07 111 views
0

我期待着开始然后停止一个setInterval,我遇到过的所有例子都用全局变量做这个,但我宁愿不使用一个,如果我可以的话。停止setInterval()没有全局变量

我有一个按钮来启动setInterval和另一个来停止它。我可以启动它就好了,但是我无法在不使用全局变量的情况下停止它。

这是我有:

function counter() { 
    function stop() { 
    clearInterval(timer); 
    } 
    var timer = setInterval(function() { 
    console.log(new Date()); 
    }, 1000); 
    return stop; 
} 
$('#start').click(function() { 
    counter(); 
}); 
$('#stop').click(function() { 
    stop(); // this of course doesn't work 
}); 
+0

与'const'或'let'一起使用块? – Li357

+2

在IIFE中包装整个东西 – Pointy

+0

您应该将stop函数移出计数器函数,以便在$('stop')内调用它。click(function(){}) – user93

回答

0

你需要一个全局变量,但你可以在很多方面做,所以这里的做法,HTML部分:

<button id="start">Start</button> 
<button id="stop">Stop</button> 

和JS部分:

function timer() { 
    var timer = null; 
    function stop() { 
    clearTimeout(timer); 
    } 

    function start() { 
    timer = setInterval(function(){ 
     console.log("repeat it"); 
    }, 500);  
    } 

    return { 
     stop, 
    start 
    }; 
} 

var t = timer(); 

var startBtn = document.getElementById("start"); 
var stopBtn = document.getElementById("stop"); 

startBtn.addEventListener("click", function(){ 
    t.start(); 
}, false); 

stopBtn.addEventListener("click", function(){ 
    t.stop(); 
}, false); 

这里有一个demo

1

我认为你需要一个静态变量。但不幸的是,JavaScript不支持静态变量。但是,我们可以创建一个。因为在JavaScript函数被解释为对象,所以他们可以有静态范围变量。

function counter() { 
 
    if (typeof counter.timer == 'undefined') { 
 
     counter.timer = 0; 
 
    } 
 
    counter.timer = setInterval(function() { 
 
     $("#output").text(new Date()); 
 
    }, 1000); 
 
} 
 

 
function stop() { 
 
    clearInterval(counter.timer); 
 
} 
 
$("#start").on('click', function() { 
 
    counter(); 
 
}); 
 
$("#stop").on('click', function() { 
 
    stop(); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button type="button" id="start">start</button> 
 
\t <button type="button" id="stop">stop</button> 
 
    <p id="output"></p>

0

您可以使用Java脚本闭包对于这一点,改变你的代码如下:

function counter (action, tId) { 
    var timer =setInterval(function() { 
    console.log(new Date()); 
}, 1000); 
if(typeof tId!="undefined") 
    window.clearInterval(tId); 
    return function() { 
    if(action=='stop'){ 
    counter('stop', timer) 
    } 
    } 
} 

$('#start').click(function() { 
    counter('start'); 
}); 
$('#stop').click(function() { 
    counter('stop'); 
}); 

我们做的其实什么是重新调用带间隔功能-id如果行动停止。

+0

我测试了这个,它没有工作。它只是触发另一个setInterval()。 – Err

+0

那么在返回函数里面会将当前Timer作为参数传递给tId,因为tId不会再被定义,所以它会清除Interval。 –