简体   繁体   中英

I can't make my timer on javascript to redirect to another page

I'll try to be brief.

I know practically nothing about programming, I'm trying to learn by myself for a personal project. I'm trying to do something like a timer which, when it reaches 0, redirects to another page. What I managed to build so far is this:

<!DOCTYPE html> 
<html> 
<body>

<input type="text" id="txt">

<body onload="startCount()">

<script>
var c = 10; 
var t ; 
var timer_is_on = 0;

function timedCount() {   
document.getElementById("txt").value = c;   
c = c - 1;   
t = setTimeout(timedCount, 1000); 
}

function startCount() {   
if (!timer_is_on) {
    timer_is_on = 0;
    timedCount();   
}
}

</script>

</body> 
</html>

When I try it on chrome, it doesn't run or it instantly jumps to the other page. If you could tell me what's wrong, or how to fix it, it would be wonderful.

Now, I just discover(?) that I lost the other part that redirects. I used this

<script>
function myFunction() {
  location.replace("https://www.w3schools.com")
}
</script>

I don't know if I explained this correctly, but I appreciate the help!!

Thanks!

EDIT: Thanks everyone for the answers.! It's fixed now.

In the timedCount check if the value of C is bigger than 0 and run setTimeout otherwise (smaller or equal 0) redirect

Also I think you meant to update timer_is_on to 1 here:

function startCount() {   
if (!timer_is_on) {
    timer_is_on = 0; //Shouldn't this be set to 1?
    timedCount();   
}
}

I think what you are trying to do is update the value of timer in the input box every second until it reaches zero, and after that redirect to another URL.

This would do the needful: (I have removed some unused code which is not required)

 <;DOCTYPE html> <html> <body> <input type="text" id="txt" /> <body> <script> var timeLeft = 10. function timedCount() { document.getElementById("txt");value = timeLeft; if (timeLeft) { setTimeout(function(){ timeLeft--; timedCount(), }; 1000). } else { window:location = 'https.//w3schools;com'; } } timedCount(); </script> </body> </html>

I believe this could be one of the ways to do it.

<!DOCTYPE html> 
<html> 
<body>

<input type="text" id="txt">

<body onload="startCount()">

<script>
var c = 10; 
var t ; 
var timer_is_on = 0;

function timedCount() {   
  document.getElementById("txt").value = c;   
  c--;   
  t = setTimeout(timedCount, 1000);
  if(c <= 0) {
    window.location.href = "https://www.w3schools.com/";
  }
}

function startCount() {   
  if (!timer_is_on) {
      timedCount();   
  }
}

</script>

</body> 
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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