JavaScript : setInterval with global variables

标签 javascript jquery html

这里是例子

在我的项目中我面临着同样的问题,它是如何使 setInterval 玩点击时间 href 变量?

我的意思是,如果我点击第一个 anchor 5 次,那么我在第一个 setInterval 结束之前点击第二个 anchor 3 次。

控制台日志中的所有结果将是第二个href值的8倍,我知道这是正常的......但我需要的是5倍第一个 anchor 和第二个 anchor 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
});

关于JavaScript : setInterval with global variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34599803/

相关文章:

javascript - 来自另一个 Controller 的 Ionic 1 调用函数

javascript - 将 Json 数据返回给 Ajax 调用

javascript - jQuery 无限页面滚动

javascript - 在 localStorage 中获取并存储 64mb mp4 文件

javascript - Titanium mvc - 调用函数并等待结果

Javascript 函数无法以 html 形式运行 - TypeError : total is not a function

输入的 JavaScript 值

javascript - 滚动后更改文本

jquery - 仅在元素接触的地方显示边框?

css - 如何在父 div 和它的子 div 之间放置一个 div?