2

我需要有人告诉我如何取消或清除此功能的计时器。

//Html
    <a id="button" data-url="http://url.com">Click me!</a>

    Redirecting in <span id="timer"></span> seconds...
    <a href="javascript:void(0)" class="cancel">Cancel</a>
// jS
    $('a#button').click(function() {
        var url = $(this).attr("data-url");
        if( url.indexOf("http://")!==0 ){
                url = "http://"+url;
            }
        var seconds = 5,
            el = $('#timer')
        el.text(seconds)
        setTimeout(function countdown() {
            seconds--
            el.text(seconds)
            if (seconds > 0) {
                setTimeout(countdown, 1000)
            }
            else {
                window.open( url , "_self" )
            }
        }, 1000)
    })


    $('a.cancel').click(function(){
        clearTimeout(countdown);
    });

还告诉我我做错了什么以及为什么这不起作用。

4

5 回答 5

4

你需要这样做:

  var myTime;
    $('a#button').click(function() {
    var url = $(this).attr("data-url");
    if( url.indexOf("http://")!==0 ){
            url = "http://"+url;
        }
    var seconds = 5,
        el = $('#timer')
    el.text(seconds)


myTime = setTimeout(function countdown() {
        seconds--
        el.text(seconds)
        if (seconds > 0) {
            myTime =setTimeout(countdown, 1000)
        }
        else {
            //window.open( url , "_self" )
            alert('no');
        }

}, 500);

})


$('a.cancel').click(function(){
        clearTimeout(myTime);

});
于 2012-06-20T18:35:55.727 回答
3

添加:

var myTime;

myTime = setTimeout(function countdown() {...

清除它:

clearTimeout(myTime);
于 2012-06-20T18:36:50.577 回答
1

one way to do it nicely is:

{
var myTime;
myTime = setTimeout(function countdown() {
//blah
alert('Test');
clearTimeout(myTime);
}, 500);
}

then your variables are simply scoped.

于 2012-06-20T18:39:32.923 回答
1

I would do it like this : (edit: check it here http://jsfiddle.net/URHVd/3/ and it works fine)

var timer = null; //this will be used to store the timer object
var seconds = 5;
var url = null;

function countdown() {
    seconds--;

    el.text(seconds);
    if (seconds > 0) {
        timer = setTimeout(countdown, 1000)
    }
    else {
        window.open( url , "_self" )
    }
}

$('a#button').click(function() {
    url = $(this).attr("data-url");

    if( url.indexOf("http://")!==0 ){
        url = "http://"+url;
    }        
    el = $('#timer');
    el.text(seconds)
    timer = setTimeout(countdown, 1000)
})


$('a.cancel').click(function(){
    clearTimeout(timer);
});​
于 2012-06-20T18:41:59.003 回答
1

告诉setTimeout要清理什么:

countdown = setTimeout(function countdown() {...}

确保countdown在脚本之上声明,以便它在click处理程序中可用。

于 2012-06-20T18:36:42.590 回答