How to keep timer running when alert is displayed in javascript

百般思念 提交于 2019-12-25 00:07:04

问题


I am having a Javascript function which displays timer. Now,when timer reaches 2 minutes, I want to display a alert and continue my timer function. But,my timer function stops till user clicks 'Ok' and then resumes from 1:59 secs.

Can anyone tell me how to keep the timer function running while popup box is displayed?

Here's my function to display timer.

var minutes=5;
var seconds=59;

function time_display(){
  if(minutes==2 && seconds==0){
    setTimeout('display_time_alert_two_minutes_left()',100);
  }
  if (seconds<=0){
    seconds=59;
    if(minutes>0)
      minutes-=1;
  }
  else
    seconds-=1;
  $('time_left_in_minutes').innerHTML = minutes+"."+ ljust_zero(seconds);
  setTimeout("time_display()",1000);
}
time_display();

and this is my alert function.

function display_time_alert_two_minutes_left(){
    alert('Two minutes left');
}

回答1:


Alert is a blocker, use custom javascript popups like lightbox,lytebox,jquery dialog,fancybox etc.

Or you can simply show/hide a floating div. This will solve the problem of your timer getting stuck, and also enhance your user experience.




回答2:


How about you use something thats no so intrusive, something like this




回答3:


As alert() stops the rest of the javascript code executing, it would be better to use something that doesn't require an imperitive style of incrementing time.

How about you actually use the time/date functionality, which will 'keep counting'?

Edit : This will stop the web page updating when you call alert() but it will keep counting fine whilst an alert is open.



来源:https://stackoverflow.com/questions/5194231/how-to-keep-timer-running-when-alert-is-displayed-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!