如何取消 setTimeout ? [英] How to cancel setTimeout from this?

查看:158
本文介绍了如何取消 setTimeout ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need someone to tell me how to cancel or clear the timer on this function.

//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);
    });

另外告诉我我做错了什么以及为什么这不起作用.

Also tell me what I"m doing wrong and why this isn't working.

推荐答案

你需要这样做:

  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);

});

这篇关于如何取消 setTimeout ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆