简体   繁体   English

javascript中的多个if-else语句,用于计时器

[英]Multiple if-else statement in javascript for timer

I have a problem with the if-else statement in the code given below. 我在下面的代码中使用if-else语句遇到问题。 The code below shows a reverse counter from 15 seconds. 下面的代码显示15秒后的反向计数器。 Now when the counter hits to 10 seconds, it should show a message ("You will be logged out in 10 seconds"). 现在,当计数器达到10秒时,它应该显示一条消息(“您将在10秒后注销”)。 The counter shouldn't stop and when it hits 0 seconds, it should redirect to some other page. 计数器不应该停止,并且当它达到0秒时,它应该重定向到其他页面。 The below code works till the time it reaches 10 seconds and shows the message. 下面的代码可以工作到10秒钟,并显示此消息。 After that, it just stops. 之后,它就停止了。 How can I make it work... (add break, continue in the code?) 我如何使其工作...(添加中断,在代码中继续?)

function setCookie(cname,cvalue,exdays)
{
    var d = new Date();
    d.setTime(d.getTime()+(exdays*24*60*60*1000));
    var expires = "expires="+d.toGMTString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname)
{
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) 
    {
        var c = ca[i].trim();
        if (c.indexOf(name)==0) return c.substring(name.length,c.length);
    }
return "";
}

//check existing cookie
cook=getCookie("my_cookie");

if(cook==""){
    //cookie not found, so set seconds=60
    var seconds = 15;
}else{
    seconds = cook;
    console.log(cook);
}

function secondPassed() {
            var minutes = Math.round((seconds - 30)/60);
            var remainingSeconds = seconds % 60;
            if (remainingSeconds < 10) {
                remainingSeconds = "0" + remainingSeconds; 
            }
            //store seconds to cookie
            setCookie("my_cookie",seconds,5); //here 5 is expiry days

            document.getElementById('countdown').innerHTML = minutes + ":" +    remainingSeconds;
            if (seconds == 10) {
                clearInterval(countdownTimer);
                document.getElementById('countdown').innerHTML = "You will be logged out in 10 seconds";

            } else if (seconds == 0) {
                clearInterval(countdownTimer);
                document.getElementById('countdown').innerHTML = "Buzz Buzz";                       
                window.location="http://www.google.com";
            } else {    
                seconds--;
            }
        }
var countdownTimer = setInterval(secondPassed, 1000);

Here is the working code.. http://jsfiddle.net/e80erzk8/ 这是工作代码。.http://jsfiddle.net/e80erzk8/

  if (seconds == 10) {
            clearInterval(countdownTimer);
            document.getElementById('countdown').innerHTML = "You will be logged out in 10 seconds";
  ...

clearInterval stops the timer clearInterval停止计时器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM