首页 > 关于停定时器的问题

关于停定时器的问题

下面验证注册资本不是能为空并只能为数字
我在里面定义了一个变量timer = null
tip方法我进来就清除
不过好像清除没用?
如果我先不输入,让他提示,然后我再立马添加些字符,
他还是执行上次的定时器
有什么办法能清除,不管在函数里面外面定义都清除不了

  <div class="form-group">
        <label class="col-sm-2 control-label"><span>*</span>注册资本(万)</label>
        <div class="col-sm-7">
            <input type="text" class="form-control" id="registermoney" placeholder="请输入注册资本">
        </div>
  </div>  
  <a href="#" class="btnsubmit">提交</a>


  var v_registermoney  = utils.isStringEmpty(_registermoney.val()), 
      v_registermoney2 = utils.getNumber(_registermoney.val());
                
  tip: function (text, type, callback) {
        var  timer = null;    
        clearTimeout(timer);
        
        if (!text) return false;
        var typename = type || '';
        
        $('.softlyTipBox').remove();
        $('body').append('<div class="softlyTipBox ' + typename + '"><p>' + text + '</p></div>');
        var width = $('.softlyTipBox').find('p').width() + 160;
        
        $('body > .softlyTipBox').css({
            'width': width,
            'margin-left': - parseInt(width/2)
        })
        setTimeout(function () { 
            $('body > .softlyTipBox').addClass('show');
        }, 150);

        timer = setTimeout(function () {
            $('body > .softlyTipBox').css({
                'width': 0,
                'margin-left': 0
            });
            setTimeout(function () {
                $('body > .softlyTipBox').remove();
            }, 300);
            if (callback) callback();
        }, 3000);
    }
    
    $('.btnsubmit').click(function(){
    if(!v_registermoney){
           tip('请输入企业性质', 'error');
           return;
    }else if(!v_registermoney2){
           tip('请输入数字', 'error');
           return;
    }else{                    
       
    }
    })

我的理解,你的timer是在tip函数内部声明的内部变量,每次调用tip时都会重新var一个timer出来,因此无法将之前设置的定时器进行删除。

对于这种常用的调用定时器的方法,推荐将其使用CommonJS打包成组件:

// "tips.js"
define(function(require, exports, module) {
    var timer;
    var tip = function(..., delay) {
        if(timer) {
            window.clearTimeout(timer);
        }
        timer = setTimeout(function() {
            ...
        }, delay);
    }
    exports.tip = tip;
});

然后每一次调用的时候再把tips引用进来,这样就避免为了清除timer而污染了全局变量的方式。

// test.js
var tips = require('tips');
tips.tip(..., 3000);

if (callback) callback();

tip('请输入数字', 'error', timer);

你把 timer 作为参数传进去了。这个是 clear 不掉的。

【热门文章】
【热门文章】