在setInterval函数中传递参数并能够使用clearInterval

时间:2013-09-19 07:47:53

标签: javascript setinterval clearinterval

我知道什么

如果没有自包含它的参数,则无法将参数传递给setInterval方法,至少在IE9中。

myInterval = setInterval('startTimer(10)',500);无效

其中

setInterval( function() { startTimer(10); }, 500 );将有效。

我做了什么

    timer( $('#display-upgrade-ticker-'+response.userClubHouseDisplayId + " .display-upgrade-timer"),currentDate);

    function timer(Obj, target_date) {

        // variables for time units
        var days, hours, minutes, seconds;

        displayInterval = setInterval(function () {
            // update the tag with id "countdown" every 1 second
            var current_date = new Date().getTime();
            var seconds_left = (target_date.getTime() - current_date) / 1000;
            console.log(seconds_left);
            // do some time calculations
            days = Math.round(parseInt(seconds_left / 86400));
            seconds_left = Math.round(seconds_left % 86400);

            hours =Math.round(parseInt(seconds_left / 3600));
            seconds_left = Math.round(seconds_left % 3600);

            minutes = Math.round(parseInt(seconds_left / 60));
            seconds = Math.round(parseInt(seconds_left % 60));

            // format countdown string + set tag value
            if(hours<10) hours='0'+hours;
            if(minutes<10) minutes='0'+minutes;
            if(seconds<10) seconds='0'+seconds;

            $(Obj).html(hours+":"+minutes + ":" + seconds);

            if ( days == 0 && hours == 0 && minutes == 0 && seconds == 0 ) {
                clearInterval(displayInterval);        
            }
        },1000);
    }

我想要什么

我需要在满足if ( days == 0 && hours == 0 && minutes == 0 && seconds == 0 )条件后触发clearInterval。如果setInterval是自包含的,我该如何解决这个问题。

0 个答案:

没有答案