简体   繁体   中英

Javascript countdown timer only displays once?

I have a web app which after 1 hour of inactivity brings up a JQuery UI modal dialog with a 5 minute countdown timer. The first time this happens the timer works fine but if the user extends session and it comes up a second time, the timer does not display (but is still accessible in the console and still counts down)

Here is the code that runs when the popup is displayed:

// set countdown timer
time=5*60,r=document.getElementById('r'),tmp=time;
timer = setInterval(function(){
  var c=tmp--,m=(c/60)>>0,s=(c-m*60)+'';
  r.textContent='Time Remaining: '+m+':'+(s.length>1?'':'0')+s  
  tmp!=0||(tmp=time);
},1000);

Any ideas why it is not being displayed the second time?

The markup for this part of the app is very simple. I am creating the modal in Javascript like this:

var modal = "<div id='modal_pop'><p>"+opts.dialogText+"</p><br><br><div id='r'></div></div>";

And then each time the inactivity period is reached I am displaying it with the following code:

my_dialog = $(modal).dialog({
      buttons: buttonsOpts,
      modal: true,
      title: opts.dialogTitle
    });

Immediately after this I set up the timer using the first piece of code I submitted. Thanks for your help

You should reuse the previously created modal dialog after the first time and call its open method. Here's an example:

 $(document).ready(function () { var opts = { dialogText: 'Modal Dialog', dialogTitle: 'Title' }; var modal = "<div><p>"+opts.dialogText+"</p><br><br><div class='remaining'></div></div>"; var dialog; var interval; var secsToRemainingTime = function secsToRemainingTime(secs) { var mm = ('0'+~~(secs / 60)).slice(-2); var ss = ('0'+(secs % 60)).slice(-2); return mm + ':' + ss; }; var showDialog = function showDialog() { var time = 5 * 60; dialog = dialog || $(modal).dialog({ // reuse the previously created dialog or create one for the first time title: opts.dialogTitle, modal: true, autoOpen: false, close: function(event, ui) { if (interval) { clearInterval(interval); interval = undefined; } } }); dialog.dialog('open'); // http://api.jqueryui.com/dialog/#method-open var remainingDiv = dialog.children('.remaining'); remainingDiv.html(secsToRemainingTime(time)); interval = setInterval(function () { if (time == 0) { clearInterval(interval); interval = undefined; // TODO: do something return; } remainingDiv.html(secsToRemainingTime(--time)); }, 1000); } $('#show-dialog').click(showDialog); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> <button id="show-dialog">Show Dialog</button> 

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