使用倒数计时器自动刷新页面

时间:2015-01-07 20:34:04

标签: javascript c# asp.net timer updatepanel

我有一个小的C#代码,在15秒后刷新webform页面(form.aspx),如下所示:

lblMessage.Text = "<b><h2>Thank you!</h2></b></br>We will be right with you.<br><br><br>(This page will be refreshed automatically after 15 seconds)";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Success!", "setInterval(function(){location.href='/form.aspx';},15000);", true);

现在页面将在15秒后刷新。如何让计时器每秒倒计时?即,15 =&gt; 14 =&gt; 13 =&gt; ... 1然后刷新,这样对用户来说会更好,他们会知道页面发生了什么......

2 个答案:

答案 0 :(得分:3)

在javascript中我会选择这样的东西。

<div id='countdown'></div.

var countDown = 15;

function countdown() {
    setInterval(function () {
        if (countDown == 0) {
            return;
        }
        countDown--;
        document.getElementById('countdown').innerHTML = countDown;
        return countDown;
    }, 1000);
}

countdown();

小提琴:http://jsfiddle.net/chzzcosy/

答案 1 :(得分:1)

"<b><h2>Thank you!</h2></b></br>We will be right with you.<br><br><br>(This page will be refreshed automatically after <span id='counter'>15</span> seconds)"

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Success!", "setTimeout(function(){location.href='/form.aspx';},15000); counter = 15; setInterval(function(){counter--; document.getElementById('counter').innerHTML = counter;},1000);", true);

应该这样做。

如果在刷新消息编号周围添加span id counter

然后我添加了counter = 15;来初始化默认值15.而另一个setInterval到脚本块每秒都会触发。每次传递时,它会从counter中减去一个,并使用新的计数器值更新span。用户现在应该看到页面倒计时。我还将第一个setInterval更改为setTimout,因为它在技术上是超时而不是每15秒应该发生一次的间隔。

相关问题