douliandan7340 2015-09-14 08:55
浏览 107
已采纳

如何在点击按钮时停止计时器并在php javascript中获取计时器值

var n = 60;
setTimeout(countDown, 1000);
function countDown(){
    n--;
    if (n > 0){
        setTimeout(countDown, 1000);
    }
    //alert(n);
    document.getElementById("div_timer").innerHTML = n; 
}            

this is my code for count down timer. when clicking the submit button, i need to stop the counter running and should return the counter value. please help...

  • 写回答

1条回答 默认 最新

  • doudou3716 2015-09-14 09:08
    关注

    Instead of using setTimeout, use setInterval and assign it to a variable, so you can clear it with clearInterval by passing the variable you therefore defined as argument.

    For example :

    var n = 10; 
    var f = setInterval(function() { 
        console.log("foo"); 
        n--; 
        if (n<=0) { 
            clearInterval(f) 
        }
    }, 1000);
    

    Then in your button click handler, just do a

    clearInterval(f) 
    

    and you'll get the right n value.

    Also note that the first step of the interval is occuring after 1s in my example, which technically makes n reaches 0 after 11s, not 10.

    For the following, as your title is a bit weird (javascript php ?), after you get the n value, do an Ajax request to some php-server with n value as a parameter. But I think this should belong to another question.

    Br.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?