admin管理员组

文章数量:1393066

Hi i am using Javascript set timeout to run a certain function.

How do i display the last 10 seconds of the timeout when it is nearing the end?

var a = setTimeout('someFunction()', 10000);

Is it able to display something using the value that it store into the variable?

Thanks

Hi i am using Javascript set timeout to run a certain function.

How do i display the last 10 seconds of the timeout when it is nearing the end?

var a = setTimeout('someFunction()', 10000);

Is it able to display something using the value that it store into the variable?

Thanks

Share Improve this question asked Aug 10, 2011 at 9:27 DayzzaDayzza 1,5677 gold badges18 silver badges30 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4

I have created a small demo for you,

http://jsfiddle/praveen_prasad/DYaan/1/

<div id="target" style="display:none">
    target
</div>


var target,
    allotedTimeForWork=100   /*you can change this*/
    ;
var handler = setTimeout(function(){
      if(!target)
      {
          target=document.getElementById('target');
      }
    target.style.display="block";
    startTicker();
}, allotedTimeForWork);

function startTicker()
{
    var counter=10;
    var tickerHandler= window.setInterval(function(){
          if(counter>0)
          {
              //cache target
              target.innerHTML="you have "+counter +" seconds left";
              counter--;
          }
        else
        {
            target.innerHTML="time over";
            clearInterval(tickerHandler);
        }
    },1000);          
}

It is not possible to directly get the remaining time of a Timeout. You could either try to make multiple Timeouts for every second, or have another variable where you store when the Timeout was started.

I would use two timeouts.

The first with time minus 5 seconds, that calls a function with the second timeout (5 seconds) which would have the timer displayed.

Take a look here: http://jsfiddle/VCAnm/

HTML:

<span id="aaa">10</span>

JavaScript:

setInterval(function() {
    var elem = document.getElementById('aaa');
    elem.innerHTML = elem.innerHTML - 1;
}, 1000);

set 2 timers one for the timeout and another for the warning

var warn_time = 5000;
var function_name = 'someFunction()';

var a = setTimeout('warnFunction(function_name, warn_time)', 10000 - warn_time);

function warnFunction(function_name, time) {
  alert('only ' + time + ' seconds left');   //use a div or whatever to display
  var b = setTimeout(function_name, time);
}

本文标签: javascriptHow to show last 5 seconds when timing is running outStack Overflow