3

Добрый день! Есть скрипт редиректа с таймером обратного времени. В скрипте задаешь время, и он при открытии страницы отсчитывает время. Когда доходит до нуля, то продолжает считать уже в минусе. Как сделать, чтобы он доходил до нуля, и после этого span id timer_page2 становился display:none? Помогите, пожалуйста. Спасибо!

var time = 12;
var page = "#page2";

function countDown(){
    time--;
    gett("timer_page2").innerHTML = time;
    if(time == 0){
        window.location = page;
    }
 }

 function gett(id){
    if(document.getElementById) 
        return document.getElementById(id);
    if(document.all) 
        return document.all.id;
    if(document.layers) 
        return document.layers.id;
    if(window.opera) 
        return window.opera.id;
 }

 function init(){
    if(gett('timer_page2')){
        setInterval(countDown, 1000);
        gett("timer_page2").innerHTML = time;
    } else {
        setTimeout(init, 50);
    }
}

document.onload = init();

<span id='timer_page2'></span>

1 ответ 1

1

Можно воспользоваться функцией clearInterval:

var timer;
var time = 12;
var page = "#page2";
function countDown() {
    time--;
    gett("timer_page2").innerHTML = time;
    if (time == 0) {
        clearInterval(timer);
        gett("timer_page2").style.display = "none";
        //gett("timer_page2").innerHTML = ""; // второй вариант!
        window.location = page;
    }
}
function gett(id) {
    if (document.getElementById) return document.getElementById(id);
    if (document.all) return document.all.id;
    if (document.layers) return document.layers.id;
    if (window.opera) return window.opera.id;
}
function init() {
    if (gett('timer_page2')) {
        timer = setInterval(countDown, 1000);
        gett("timer_page2").innerHTML = time;
    }
    else {
        setTimeout(init, 50);
    }
}
document.onload = init();
3
  • В таком случае останавливается на нуле, и ноль остается. А как же сделать, чтобы именно span id timer_page2 становился display:none? В любом случае очень благодарен вам за помощь! 19 авг 2015 в 15:16
  • Внес исправления. Там есть два варианта избавиться от 0.
    – pavelip
    19 авг 2015 в 15:21
  • Да, всё чудесно работает! Огромное вам спасибо за помощь! 19 авг 2015 в 16:07

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.