猿问

NodeJS 倒计时

我正在调用提交按钮并为每次点击添加选中的值。我想添加一个倒计时并说:

每 60 秒只计算一次用户点击。否则显示警报。


这是我的代码:


form.addEventListener('submit', (e) => {


    const choice = document.querySelector('input[name=os]:checked').value;

    const data = {os:choice}


    fetch('localhost:3000/poll', {

        method: 'post',

        body: JSON.stringify(data),

        headers: new Headers({

            'Content-Type': 'application/json'

        })

    })

        .then(res => res.json())

        .then(data => console.log(data))

    // alert("Danke für die Abstimmung")


.catch(err => console.log(err));

    e.preventDefault();


});


大话西游666
浏览 208回答 1
1回答

暮色呼如

您可以使用标志来检查时差。用户单击提交按钮后,您可以将时间存储在变量中。如果用户再次单击提交按钮,请检查当前时间和上次提交时间(存储在变量中)之间的差异。如果时间差小于 60 秒,则显示警报消息,否则执行发布请求。var submissionTime = undefined;form.addEventListener('submit', (e) => {&nbsp; e.preventDefault();&nbsp; var flag = true;&nbsp; if(submissionTime) {&nbsp; &nbsp; var milliseconds = new Date().getTime() - submissionTime.getTime();&nbsp; &nbsp; var seconds = Math.abs(milliseconds / 1000);&nbsp; &nbsp; if(seconds < 61) {&nbsp; &nbsp; &nbsp; flag = false;&nbsp; &nbsp; &nbsp; // show the alert&nbsp; &nbsp; }&nbsp; }&nbsp;&nbsp;&nbsp; if(flag) {&nbsp; &nbsp; submissionTime = new Date();&nbsp; &nbsp; const choice = document.querySelector('input[name=os]:checked').value;&nbsp; &nbsp; const data = {os:choice}&nbsp; &nbsp; fetch('localhost:3000/poll', {&nbsp; &nbsp; &nbsp; &nbsp; method: 'post',&nbsp; &nbsp; &nbsp; &nbsp; body: JSON.stringify(data),&nbsp; &nbsp; &nbsp; &nbsp; headers: new Headers({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'Content-Type': 'application/json'&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; })&nbsp; &nbsp; .then(res => res.json())&nbsp; &nbsp; .then(data => console.log(data))&nbsp; &nbsp; // alert("Danke für die Abstimmung")&nbsp; &nbsp; .catch(err => console.log(err));&nbsp; }});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答