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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?