[英]JavaScript - setInterval with passed function does not recognize global variables
[英]javascript : setInterval with global variables
在此示例中
在我的项目中,我面临着同样的问题,它是如何使setInterval
与click time href
变量一起播放的?
我的意思是,如果我单击了第一个锚点5次,那么我在第一个setInterval
结束之前单击了3次第二个锚点。
console log
中的所有结果将是第二href
值的8倍,这是正常的,我知道...但是我需要的是第一个锚点5倍和第二个锚点3倍的想法?
注意
由于某些原因, href
变量必须是全局变量
var href = null; $('a').click(function(e) { e.preventDefault(); href = $(this).attr('href'); var timeLeft = 3000; var counterInterval = setInterval(function() { timeLeft -= 20; if (timeLeft < 0) { console.log(href); window.clearInterval(counterInterval); } }, 20); })
<a href="first">first anchor</a> <a href="second">second anchor</a> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
将代码更改为此:
// You're right, href is a global variable which isn't necessary in the demonstration, you can simply remove it
// var href = null;
$('a').click(function(e) {
e.preventDefault();
// let's declare a local variable, href is local to this event
var href = $(this).attr('href');
// change your block to a self invoking function
// the key is that it accepts a parameter and we pass in the href
(function(v) {
var timeLeft = 3000;
var counterInterval = setInterval(function() {
timeLeft -= 20;
if (timeLeft < 0) {
// now we use the parameter v that was passed in
console.log(v);
window.clearInterval(counterInterval);
}
}, 20);
})(href); // <<<<<< this is where we pass in the local href to the self invoke function
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.