weixin_33691817 2017-02-25 21:43 采纳率: 0%
浏览 182

JS <(小于)运算符失败

I have a script that AJAXes a request every 10 seconds (but technically 11), for the user. I have a simple countdown made from 10 to 0 and then again and again.

This countit function is called after each AJAX request to restart

Here is my code:

function countit() {
  var count = 10;
  loading = setInterval(function() {
    $(box).val("Will automatically check in " + count + "second(s), please DO NOT refresh the page yourself.");
    count--;
    if (count <= 0) {
      clearInterval(loading);
    }

  }, 1000);
}

The code works fine except, if you leave the page and come back, the countdown proceeds into negative and does not stop. Here is the image:

enter image description here

I cant be sure if this is a problem with the code or JS but the counter doesnt go below 0 when the user stays on the page.

  • 写回答

1条回答 默认 最新

  • 游.程 2017-02-25 22:08
    关注

    As Ibrahim & Chris have said:

    Add a var infront of the Interval as without it, the variable is global.

    function countit() {
        var count = 10;
        var loading = setInterval(function() {
            $(box).val("Will automatically check in " + count + "second(s), please DO NOT refresh the page yourself.");
            count--;
            if (count <= 0) {
                clearInterval(loading);
            }
        }, 1000);
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)