反击计时器onclick javascript

时间:2017-11-22 08:36:20

标签: javascript timer onclick counter

我有一个计数脚本,我把它放在一个模态中,我在触发器上添加了onclick事件,但我的问题是计数器在页面加载时开始工作。当我在30秒后打开模态弹出窗口时,计数器显示30秒...我希望它从0开始打开模态弹出窗口 我有如下 触发



var count1=0; 
var counter1=setInterval(myTimerUp, 1000); //1000 will  run it every 1 second
function myTimerUp()
{
  count1=count1+1;
  if (count1 == 100)
  {
    clearInterval(counter);
    return;
  }

  document.getElementById("timerUp").innerHTML="This pop-up is running from "+ count1 + " secs"; // watch for spelling
}

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exModal1button" onclick="myTimerUp()">Pop-up manual trigger </button>
<span id="timerUp"></span>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

您在脚本的开头调用setInterval,因此计数器从头开始递增。

您必须在第一次调用函数时设置它。

var count1=0; 
var counter1;
function myTimerUp()
{
  //Start the setInterval only on the first time myTimerUp is run.
  if(!counter1) {
     counter1 = setInterval(myTimerUp, 1000); //1000 will run it every 1 second
  }
  count1=count1+1;
  if (count1 == 100)
  {
     clearInterval(counter1);
     return;
  }

 document.getElementById("timerUp").innerHTML="This pop-up is running from "+ count1 + " secs"; // watch for spelling
}

另外,提醒:我已修复原始代码的拼写错误:clearInterval(counter)变为clearInterval(counter1):未定义counter个变量。

答案 1 :(得分:0)

我稍微调整了你的代码,以使其正常工作

我只在点击按钮

时调用setTimeInterval

&#13;
&#13;
window.onload = loadScript();
function loadScript() {
document.getElementById("popUpButton").onclick = function() {
setInterval(myTimerUp, 1000);
}
var count1=0; 
var counter1;
function myTimerUp() {  
count1=count1+1;
  if (count1 == 100) {
     clearInterval(counter);
     return;
  }
 document.getElementById("timerUp").innerHTML="This pop-up is running from "+ count1 + " secs"; // watch for spelling
}
}
&#13;
<button type="button" id="popUpButton" class="btn btn-primary" data-toggle="modal" data-target="#exModal1button">Pop-up manual trigger </button>
<span id="timerUp"></span>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

var count1=0; 
var counter1=setInterval(myTimerUp, 1000)

由于这些行未在任何函数内定义,因此它们将在js文件加载时执行。

您可以按如下方式修改代码: -

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exModal1button" onclick="startTimer()">Pop-up manual trigger </button>

JS代码: -

var count1=0; 
var counter1;

function startTimer(){
  if(counter1) clearInterval(counter1) // to clear interval if in case you closed modal before count1 reaches 100 and reopen model again (clearInterval should have been called when modal closes)
  count1 = 0;
  counter1=setInterval(myTimerUp, 1000);
}

function myTimerUp(){
  count1=count1+1;
  if (count1 == 100)
    clearInterval(counter1);
  else
    document.getElementById("timerUp").innerHTML="This pop-up is running from "+ count1 + " secs"; // watch for spelling
}