Stop and Restart ASP.NET Timer

2019-08-30 11:03发布

问题:

I have an ASP.NET Timer control on my web page.

The timer is used as a trigger for an UpdatePanel. Once the content of this panel is loaded, I disable the Timer using Timer.Enabled = false; in the code. This disables the Timer from firing the Tick event.

I want to restart this timer if the user wishes to re-run the code on a button click. However, if I use Timer.Enabled = true; in the button click event, it only enables the timer when the page postsback. Evidently, this is not the behaviour I would like.

I tried to do the same using javascript,

var timer = $find('<%=TimerAH.ClientID %>');
timer._startTimer();
//timer.set_enabled(true);

This code also does not help. I would be grateful if someone could help me solve this issue. Thanks.

回答1:

You have these many client site functions for ASP.NET timer that you can easily use.

But be careful that Javascript function which start with underscore are private fucnctions by convention. They can be changed by the author, but i guess its safe to use as Microsoft is know to be good in providing backward compatibility.

Controlling the ASP.NET Timer Control with JavaScript

    var timer = $find(‘<%= Timer1.ClientID %>’);

    //returns the timer’s interval in milliseconds: 
    var waitTime = timer.get_interval;       

    //sets the timer’s interval to 5000 milliseconds (or 5 seconds): 
    timer.set_interval(5000);       

    //returns whether or not the timer is enabled: 
    var isTimerEnabled = timer.get_enabled();       

    //disables the timer: 
    timer.set_enabled(false);       

    //starts the timer: 
    timer._startTimer();       

    //stops the timer: 
    timer._stopTimer();