js 实现让一个按钮1分钟点击100次,超过100次不能点击

让一个按钮1分钟点击100次,超过100次不能点击,求大神解答,面试时这样想的


window.onload = function () {

    let btn = document.getElementById("btn");

    for (var i = 1; i <= 100; i++) {

        btn.onclick = (function (j) {

            return function () {

                setTimeout(function () {

                    console.log(j);//每次都是100

                }, 60000 / j);

            }

        })(i);

    }

}

但在setTimeout当中,j的值每次都是100,所以思路是不是有问题,求大佬解疑答惑


qq_花开花谢_0
浏览 814回答 1
1回答

明月笑刀无情

var times = 0;let btn = document.getElementById("btn");btn.onclick = function() {&nbsp; &nbsp; // 执行些乱七八糟的逻辑&nbsp; &nbsp; if(times >= 100) {&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; clearInterval(interval);&nbsp; &nbsp; }&nbsp; &nbsp; times +=1;}var interval = setInterval(function() {&nbsp; &nbsp; btn.onclick();},60000/100);以下是一个直接在console里面运行的测试函数:var times = 0;var interval = setInterval(function() {&nbsp; &nbsp; times ++;&nbsp; &nbsp; console.log(times);&nbsp; &nbsp; if(times == 100) {&nbsp; &nbsp; &nbsp; &nbsp; clearInterval(interval);&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }},5000/100);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript