如何让函数每 5 秒执行一次?

How to allow the function to be executed every 5 seconds?

我有这段代码,我想让 amurFunc() 每 5 秒执行一次。

执行是一个侦听器,如果用户单击 div,则会侦听。他实际上可以每 5 秒点击一次。你能帮我看看我哪里做错了吗

代码:

<div id=amur>

</div>

<script>
    document.getElementById("amur").addEventListener('click', amurFunc());
    function amurFunc() {
            var funcTimer = 0;
            while (funcTimer == 0) {
                window.open('http://google.com','_blank');
                funcTimer = 5;
                while (funcTimer > 0) {
                    setInterval(
                        function () {
                            funcTimer--;
                        }, 1000;
                    );
                }
            }
    }
</script>

这将 amurFunc() 每 5 秒启动一次

setInterval(function() {
    amurFunc();
} ,5000)

但是你想每 5 秒做什么?

你想每 5 秒打开一次页面吗?

为什么要在点击时启动它?

要在 5 秒后打开页面试试这个

setTimeout(function() {
    window.open('http://google.com', '_blank');
}, 5000);

更新

这是按钮

<input type="button" id="btn" value="">

这里是javascript

function Before5Seconds(idName) {
    var btn = document.getElementById(idName);
    btn.value = "Click to start wait 5 sec";
    btn.onclick = function() {
        this.value = "waiting ...";
        setTimeout(function() {
            After5Seconds(idName);
        }, 5000);
    };
}

function After5Seconds(idName) {
    var btn = document.getElementById(idName);
    btn.value = "Click to Go";
    btn.onclick = function() {
        window.open('http://google.com', '_blank');
        Before5Seconds(id);
    };

}

Before5Seconds('btn');

试试这个

<div id="amur" style="background-color:red">
 <p>Test</p>
</div>

var el = document.getElementById('amur');

el.addEventListener('click',amurFunc);


var clicked = 0;
var d = new Date();
var s = d.getTime();
//console.log(s);


function amurFunc(){
    if(clicked==0){
        window.open('http://google.com', '_blank');
        clicked++;
    }else{
        var clickedDate =  new Date();
        var clickedSecond = clickedDate.getTime();
        //console.log(clickedSecond-s);
        if((clickedSecond-s)>=5000){
            window.open('http://google.com', '_blank');
            s = clickedSecond;
        }

    }

}

最简单的解决方案是使用每 5 秒重置一次的标志。见下文:

//initially allowed to be clicked
var flag = true;

document.getElementById('amur').onclick = function(){
  if (flag) {
    window.open('http://google.com','_blank');
    //disable click
    flag = false;
    //after 5 secs, click will be enabled again
    setTimeout(function(){
      flag=true;
    },5000);
  }
}