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 Markdown在VScode编辑器下插入视频
  • ¥15 stm32c8t6工程,使用hal库
  • ¥100 有偿求易语言word文档取doc和docx页数方法或模块
  • ¥15 找能接spark如图片的,可议价
  • ¥15 关于#单片机#的问题,请各位专家解答!
  • ¥15 博通raid 的写入速度很高也很低
  • ¥15 目标计数模型训练过程中的问题
  • ¥100 Acess连接SQL 数据库后 不能用中文筛选
  • ¥15 用友U9Cloud的webapi
  • ¥20 电脑拓展屏桌面被莫名遮挡