js 取值 问题

 timeDown:function (time,interval,callback) {

            var timeCount=setTimeout(function () {

                (callback||new Function)();

                if(time===0){

                    clearTimeout(timeCount);

                }else{

                    time--;

                    console.log(time);

                    setTimeout(arguments.callee,interval);

                }

            },interval);

        }

以上实现一个倒计时功能

我希望这样调用


A.timeDown(60,1000,function(){

    //do something

    $("#xx").text(time)  //我希望能够获取 正在变化的time

})

首先我这么设计应该没啥问题吧?

我的问题是 ,我能否取出 timeDown里不停变化的time作为callback里的参数,应该怎么实现?

(不考虑使用一个全局变量来接收或者传递time)


偶然的你
浏览 417回答 2
2回答

慕的地6264312

代码这样写:arguments.callee不推荐使用,就像eval一样function timeDown(time,interval,callback) {    var timeCount;    var timeFun = function () {        if (time === 0) {            clearTimeout(timeCount);        } else {            time--;            timeCount = setTimeout(timeFun, interval);        }        callback && callback(time);    };    setTimeout(timeFun, interval);}timeDown(60,1000,function(time){    //do something    console.log("time:"+time);});

蓝山帝景

最好用setInterval,因为每次setTimeout都是一个新的定时器。&nbsp;下面这个不需要在全局里面加变量,也不需要在A里面加其他东西。timeDown: (function () {&nbsp; &nbsp; // 局部变量存放time值&nbsp; &nbsp; var _time = 0;&nbsp; &nbsp; function timeDown(time, interval, callback) {&nbsp; &nbsp; &nbsp; &nbsp; _time = time;&nbsp; &nbsp; &nbsp; &nbsp; // 开启定时器&nbsp; &nbsp; &nbsp; &nbsp; var timer = setInterval(function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // 执行回调&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; callback && callback();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // 判断次数&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (--_time <= 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; clearInterval(timer);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }, interval);&nbsp; &nbsp; }&nbsp; &nbsp; // 只暴露一个getTime给外部获取time值&nbsp; &nbsp; timeDown.getTime = function () {&nbsp; &nbsp; &nbsp; &nbsp; return _time;&nbsp; &nbsp; }&nbsp; &nbsp; return timeDown;})()A.timeDown(60, 1000, function () {&nbsp; &nbsp; //do something&nbsp; &nbsp; console.log(A.timeDown.getTime())&nbsp; // 使用timeDown.getTime获取到time值})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript