search

Home  >  Q&A  >  body text

javascript - How to implement click reset refresh in JS

I need a function. Click a button to start a timer. If the button is not clicked within 2 seconds, a certain p will be hidden. If the button is clicked, the timer will be refreshed. The button is within p, and the button needs to be continuously shocked to maintain the display of p.

<p>
     <button>按钮</button>
<p>
仅有的幸福仅有的幸福2776 days ago551

reply all(2)I'll reply

  • 滿天的星座

    滿天的星座2017-05-19 10:10:56

    What you mean by "clicking a button" and not clicking the button within 2 seconds should not be the same button, right?

    let flag = false, // 是否点击了按钮标志量,false为没有,true为点击了
        time = -1;
    button.onclick = function(){
       setInterval(function(){
            time ++;// 开始计时
            if(flag && time <= 2){ // 如果点击了按钮
                // time = 0;// 刷新计时器
                flag = false;
            }else{
               // 隐藏p        
            }
        },1000);
    }
    

    reply
    0
  • PHP中文网

    PHP中文网2017-05-19 10:10:56

    <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>时间</title>
      </head> 
    <body>
    <p>
        <button id="btn">按钮</button>
    <p>
    <script>
        let btn = document.getElementById("btn");
        let time;
        // 这行去掉就好了
        /*
        time = setTimeout(function () {
            btn.style.cssText = "display: none;"
        }, 2000);
        */
        btn.onclick = function () {
            clearTimeout(time);  
            time = setTimeout(function () {
              btn.style.cssText = "display: none;"
              clearTimeout(time);
            }, 2000)
        }
    </script>
    </body>
    </html>

    reply
    0
  • Cancelreply