0

I'm tying to create a countdown timer for online test using JavaScript in asp.net core. I want it to change every 1 second without refreshing the page. when I run the program it doesn't show me the countdown.

This my javascript code:

<script type="text/javascript">
    countdown = function () {
    var current = parseInt(document.getElementById("timerLabel").innerHTML);
    document.getElementById("left").innerHTML = current;
    if (current > 0) {
        setTimeout('countdown()', 1000); // run every second
    }}

This is my view: I used foreach loop to show this.

 <div class="panel-footer">
            <p>   @item.Grade</p>
            <p>  @item.StartTime</p>
            <p id="EndTime">  @item.EndTime</p>
            <span id="timerLabel">@ViewBag.LeftTime</span>
            <p id="left"></p>
        </div>

1 Answer 1

2
  1. Do not get the timerLabel value inside the function unless you also set it

  2. Use interval and clear it when done

let current = parseInt(document.getElementById("timerLabel").innerHTML);
const countdown = function() {
  document.getElementById("left").innerHTML = --current || "Done"; // using current when 0 it is false
  if (current <= 0) clearTimeout(tId); // stop the interval
};
const tId = setInterval(countdown, 1000)
<span id="timerLabel">10</span>
<p id="left"></p>

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you.It works. but how can I use my own left time dynamically from database?
My code will work with your @ViewBag.LeftTime My 10 is just an example
Assuming @ViewBag.LeftTime is in seconds - if not let me know
my code does't work with viewbag but it works with 10.
The please tell me what view source shows in that p
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.