Category Archives: Timer

Timer

How to place an indicator for how much time is left

Hello,

I have a web page with a displayed google map and every several seconds the values are updated automatically on the map. Can anybody tell me please how to place an indicator that will show how much time is left for the next update?

For the timer I have this in the java script

 var tim=<%= Session["21"] %>*1000;

        setInterval(function(){ initialize();}, tim);

Thanks

You can try with the below code

Change the number passed to the function "startCountdown’ found in the body tag to the amount of seconds you want.

<html>
<head>
<title></title>
<script>
    function startCountdown(timeLeft) {
        var interval = setInterval( countdown, 1000 );
        update();

        function countdown() {
            if ( --timeLeft > 0 ) {
                update();
            } else {
                clearInterval( interval );
                update();
                completed();
            }
        }

        function update() {
            hours   = Math.floor( timeLeft / 3600 );
            minutes = Math.floor( ( timeLeft % 3600 ) / 60 );
            seconds = timeLeft % 60;

            document.getElementById('time-left').innerHTML = '' + hours + ':' + minutes + ':' + seconds;
        }

        function completed() {
          alert('Time Up!');
          //Your Logic here
        }
    }
</script>
</head>
<body onload="startCountdown(20);">
Time Left <span id="time-left"></span>
</body>
</html>

Hi A2H,

I tailored your code to mine but it doesn’t update anything, not only the time left but neither the infoboxes that were updated before. Here is my code now:

 function startCountdown(timeLeft) {
            var interval = setInterval( countdown, tim*1000 );
            update();

            function countdown() {
                if ( --timeLeft > 0 ) {
                    update();
                } else {
                    clearInterval( interval );
                    update();
                    completed();
                }
            }

            function update() {
                hours   = Math.floor( timeLeft / 3600 );
                minutes = Math.floor( ( timeLeft % 3600 ) / 60 );
                seconds = timeLeft % 60;
                 setInterval(function(){ initialize();}, tim*1000); 

                document.getElementById('time-left').innerHTML = '' + hours + ':' + minutes + ':' + seconds;
            }

            function completed() {
                alert('Time Up!');
                //Your Logic here
                //setInterval(function(){ initialize();}, tim*1000);
            }
        }
...
..
<body onload="initialize()"; "startCountdown(20)"; style="padding: 1em">
...
...
Time Left <span id="time-left"></span>

nat06

<body onload="initialize()"; "startCountdown(20)"; style="padding: 1em">

Hi nat06,

Thanks for your post.

I see some syntax error in your code, please correct it and try again

<body onload="initialize(); startCountdown(20)" style="padding: 1em">

Hope this helps, thanks.

Best Regards!

Thanks Fuxiang, I tried like that as well, but again the time is not showing, I see only

Time Left as if <span id="time-left"></span> didn’t exist

The problem is you are using a variable called "tim" and you didn’t declare that variable anywhere in the code. You need to declare that variable and assign a value to it.

Please use the below updated code

<html>
<head>
<title></title>
<script>
   function startCountdown(timeLeft) {
             //Declare the variable and provide a time
             var tim =10;
            var interval = setInterval( countdown, tim*1000 );
            update();

            function countdown() {
                if ( --timeLeft > 0 ) {
                    update();
                } else {
                    clearInterval( interval );
                    update();
                    completed();
                }
            }

            function update() {
                hours   = Math.floor( timeLeft / 3600 );
                minutes = Math.floor( ( timeLeft % 3600 ) / 60 );
                seconds = timeLeft % 60;
                 setInterval(function(){ initialize();}, tim*1000); 

                document.getElementById('time-left').innerHTML = '' + hours + ':' + minutes + ':' + seconds;
            }

            function completed() {
                alert('Time Up!');
                //Your Logic here
                //setInterval(function(){ initialize();}, tim*1000);
            }
        }
  function initialize()
  {}
</script>
</head>
<body onload="initialize(); startCountdown(20);">
Time Left <span id="time-left"></span>
</body>
</html>

No, I have already declared it but I didn’t post it with the code. But thanks anyway.

[RESOLVED]Anyone recommend a smooth, fast moving CSS image carousel?

Hi

Can anyone recommend a smooth, fast moving (CSS only?) image carousel so I can replace the 6 light-grey emblem strip every 4 seconds at the bottom of
www.orbisoft.com?

(It’s just one png 935×90 but I want to add a few more.)

TIA

Mark

So every four seconds you want to replace the existing image within that area with another image?

There are obviously tons of different options out there, although you are likely going to be limited with regards to CSS only approaches (the most common would rely on Javascript or jQuery) :

If you don’t want to use Javascript / jQuery, there are other options that rely strictly on CSS and HTML as well (some use Javascript for cross-browser compatability): 

Barebones Pure Javascript Implementation

It should be noted that you could easily build your own very simple one using a bit of Javascript as follows :

<!-- Your "Slider" -->
<img id='slider' style='height: 90px; width: 935px' />
<script type='text/javascript'>
    // Indicate the current image you are on
    var currentImage = 0;
    
    // An array of your images
    var images = [];
    
    // Set the path for each of your images here (examples with that same size)
    images.push('...');
    images.push('...');
    images.push('...');
    images.push('...');

    // Initialize your first image
    UpdateImage(0);
    
    // Set a timer to update your image every 4 seconds
    setInterval(function(){ UpdateImage(currentImage);}, 4000);
    
    // A function to update your image
    function UpdateImage(index){
        // Set the image to the current image
        document.getElementById('slider').src = images[index];
      
        // Increment the current image (and handle resetting to 0)
        currentImage = (currentImage != images.length - 1) ? currentImage + 1 : 0;
    }
</script>

You can see a working example of this here, albeit it is the most basic of implementations for something like this.

Example Implementation "Basic jQuery Slider"

A very simple implementation using a plug-in might be like the following one based on the
Basic jQuery Slider :

<!-- Stylesheet for this plug-in -->
<link rel="stylesheet" href="http://www.basic-slider.com/css/main.css">
<!-- jQuery Reference -->
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!-- Slider Script -->
<script src="http://www.basic-slider.com/js/bjqs-1.3.min.js"></script>
<!-- Slider configuration -->
<script type='text/javascript'>
      $(function(){
         // When your page loads, set up the slider
         $('#my-slideshow').bjqs({
           'height' : 90,
           'width' : 935,
           'showcontrols': false,
           'showmarkers': false,
           'responsive' : true
         });
      });
</script>
  
</head>
<body>
  <!-- Your Slideshow -->
  <div id="my-slideshow">
    <!-- Place each image within this list -->
    <ul class="bjqs">
        <li><img src='...' style='height: 90px; width: 935px' /></li>
        <li><img src='...' style='height: 90px; width: 935px' /></li>
       <li><img src='...' style='height: 90px; width: 935px' /></li>
       <li><img src='...' style='height: 90px; width: 935px' /></li>
    </ul>
  </div>
</body>

You can see a working example of this here, which is probably more what you are looking for. (The transitions can be configured as well).

Excellent response IMO. Thank you.

Problem in stored procedure in mvc

Hi,

iam trying to convert a web application in to  MVC .

my requirement is ,i want to display records from a stored procedure in to a table format .

stored procedure contains a complex select query.

i have read some tutorial in which contains we can’t read data using storedprocedure in mvc.is it true.

then how to solve my problem

Regards

Baiju

klbaiju

have read some tutorial in which contains we can’t read data using storedprocedure in mvc.is it true.

false.

More, MVC does not matter how you obtain data. MVC View display a Model. Just make a class that reads the SP.

Do you know how to read the records from SP ? 

hi ignatandrei,

i already use sp to insert,update and delete in mvc.

here it is a select query in sp. also pivot query and don’t know the field names .

then how to write class in model and write fieldnames in view

1. You get DataTable or DataReader and populate List<yourcomplextype> by iterating you row from datatable or datareader
2. pass it to view from the controller

public class contact
{
    public string Name { get; set; }
    public string Address { get; set; }
}
public ActionResult GetList()
{
    List<contact> contacts = new List<contact>();

    DataSet ds = new DataSet("TimeRanges");
    using (SqlConnection conn = new SqlConnection("ConnectionString"))
    {
        SqlCommand sqlComm = new SqlCommand("Procedure1", conn);
        sqlComm.Parameters.AddWithValue("@paramname", paramvalue);
        //....
                
        sqlComm.CommandType = CommandType.StoredProcedure;

        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = sqlComm;

        da.Fill(ds);
                
        foreach(DataRow dr in ds.Tables[0].Rows)
        { 
            contact contact = new contact();

            contact.Name = dr["Name"].ToString();
            contact.Address = dr["Address"].ToString();

            contacts.Add(contact);
        }
    }
    return View(contacts);

}

hi cnuonline your code will work if we know the field names.

klbaiju

hi cnuonline your code will work if we know the field names.

Then don’t use list of complex objects , use list of strings.And add them to the view then iterate the html table attribute to display the records.

klbaiju

here it is a select query in sp. also pivot query and don’t know the field names

@using System.Data;
@model System.Data.DataTable
<table>
    <tr>
        @foreach (DataColumn dc in Model.Columns)
        {
            <th>@dc.ColumnName</th>
        }
    </tr>
   
    @foreach (DataRow dr in Model.Rows)
    {
        <tr>
            @foreach (DataColumn dc in Model.Columns)
            {
                <td>@dr[dc.ColumnName]</td>
            }
        </tr>
    }
   
</table>

Hi cnuonline,

any need of class file in model.

and what code should i write in controller

klbaiju

any need of class file in model.

Data table is the model for the view

klbaiju

and what code should i write in controller

refer the my first reply

Hi cnuonline,

i have solved my problem as per your example.

this is the code

code in controller

 public ActionResult Index()
        {

using (SqlConnection conn = new SqlConnection(@"Data Source=baiju-pcsqlexpress;Initial Catalog=MvcApplicationDataBase.Models.SimpleBookCatalog;Integrated Security=True"))
            {
                SqlCommand sqlComm = new SqlCommand("select * from dbo.books", conn);
               

                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = sqlComm;
                DataSet ds = new DataSet();
                da.Fill(ds);
                DataTable dt = ds.Tables[0];
                return View(dt);
            }

}

code in view

@model System.Data.DataTable
@using System.Data;

<h2>Report</h2>
<html>
<head>
<title>SQLQueryExample</title>
<style type="text/css">
table,th,td{border:1px solid black;border-collapse:collapse;}


</style>
</head>
<body>
<table>
    <thead>
    <tr>
    @foreach (DataColumn col in Model.Columns)   
    {         
        <th>@col.ColumnName</th>
    }    
    </tr>
    </thead>        
    <tbody>
    @foreach (DataRow row in Model.Rows)    
    {        
        <tr>
        @foreach (DataColumn col in Model.Columns)        
        {             
            <td>@row[col.ColumnName]</td>
           
        } 
         <td>@Html.ActionLink("Edit", "Edit", new { id = @row[0] }) |</td>
          <td>@Html.ActionLink("Delete", "Delete", new { id = @row[0] }) |</td>
           <td>@Html.ActionLink("Details", "Details", new { id = @row[0] }) </td> 
        </tr>
    }    
    </tbody>
</table>
</body>
</html>

this is working fine.

is this the right way of doing this kind of example in mvc.

is this completely follows mvc principle.

plz reply soon

Regards

Baiju

Here you are not violating any asp.net mvc rule.

SqlCommand sqlComm = new SqlCommand("select * from dbo.books", conn);

You have a few options which have been shown, If it was me I would open the database and look in the table called books and from there you can specify what the column names are and build a class around that and pass it to your view as a list.

The other things which is entirely up to you of course but from my preference I prefer to put SQL connections in a separate class within a folder called DataAccess of something more meaningful.

[RESOLVED]When using JQuery with JSON calling a webmethod, what is the best way of handling timing for the client side to wait for data returned from the server?

I am looking in general at the best way to detect when a script on the client side calling a webmethod in codebehind has received the data on the client side.

I have to use an alert to stop the script, and in doing so it works because of creating enough pause.  I have created a timer, but I would rather have something detect it has returned

function getData() {
var pal = [];
var request = $.ajax({ type: 'POST',
url: '/App_Pages/index.aspx/getData',
data: "{MyID: '1'}", contentType: "application/json; charset=utf-8", dataType: "json", }); request.done(function (data) { // alert('done'); // alert(data.d); var MyData = data.d; for (var i = 0; i < MyData.length - 1; i++) { pal.push(MyData[i]); } }); request.fail(function (jqXHR, textStatus) { alert("Request failed: " + textStatus); });
alert('pause'); alert(pal[3]);
}

If I have the alert(‘pause’); uncommented, I get a value for alert(pal[3]);

If I comment out the alert("pause"); I get an undefined value for alert(pal[3]);

I know it is a timing issue but what is the best way to sense that the data has been returned?

What is happening is that your ajax call is asynchronous. Your getData() function will execute line by line. So your essentially calling console.log(pal[3]) before the data has returned from the server. Your request.done() is the callback. This fires after
the data has been received from the server. To Accomplish what you want you need to move the alert into the call back:

request.done(function (data) {
                //  alert('done');
               // alert(data.d);
                var MyData = data.d;
                for (var i = 0; i < MyData.length - 1; i++) {
                    pal.push(MyData[i]);

} alert('pause'); alert(pal[3]); });

hope it helps!

[RESOLVED]Using Flip effect in DataList (C#) asp.net ?

Hi,

I have created a Data List in Asp.net C# and i have used a Timer and Ajax control to update the data automatically after 10 seconds.

When a data is updated for a particular value in Datalist i need to used the Flip effect for updating data.

Any ideas ?

Hi Raghu,

Are you looking for something like this in your td element:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Data List</title>
    <style type="text/css">
        .flipY {
        
        transform:rotateY(180deg);
        background-color:blue;
        }
        .flipBack {
        transform:rotateY(180deg);
        background-color:red;
        }
        #change {
        height:100px;
        width:200px;
        background-color:red;
        }
    </style>
    <script type="text/javascript">
        function initialize()
        {
            
            var t = self.setInterval(function () {
                document.getElementById('change').style.transform = "rotateY(180deg)";
                document.getElementById('change').style.backgroundColor = "blue";
            }, 5000);
            var h = self.setInterval(function () {
                document.getElementById('change').style.transform = "rotateY(360deg)";
                document.getElementById('change').style.backgroundColor = "red";
            }, 10000);
        }

    </script>
</head>
<body onload="initialize()">
    <form id="form1" runat="server">
    <div id="change">
    what in the world!
    </div>
    </form>
</body>
</html>

using transform proeprry in css3, a div element can be flipped horizontally or vertically .

Working Demo

Hope this helps.

[RESOLVED]Popup for Process

Hi,

I want to show popup box for process until the process is done from server.

Example: adding product from admin , so until process done i want to show popup on the middle of the page and user cannot click until process done.

Please, I need your suggestions and logic to achieve my scenario.

Appreciate for your Quick and Better response.

Hi smd_yasin,
Based on your post, you want to show a box as a processbar, and user cannot click until process done. If I understand correctly, you’d better to try my code as below.

<head runat="server">
    <title></title>
    <style type="text/css">
    .lblTxtCenter
         {
              text-align: center;
         }
    </style>
    <script type="text/javascript" src="/jquery/jquery.js"></script>
    <script type="text/javascript">
        //$(document).ready(function ()
        //{
        //    $("#Button1").click(function ()
        //    {
        //        $("#Button1").attr({ "Enable": "false" });
        //    })
        //})// this JQuery is used to disable Button1 until process done
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <div class="pro">
         <asp:UpdatePanel ID="UpdatePanel1" runat="server" Visible="False">
             <ContentTemplate>
                 <div style='width: 200px; background-color: Silver; height: 20px;'>
                     <asp:Label runat="server" ID="lbl" CssClass="lblTxtCenter"></asp:Label></div>
                 <asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick" Enabled="false">
                 </asp:Timer>
                 <br/>
             </ContentTemplate>
         </asp:UpdatePanel>
        </div>
         <asp:Button ID="Button1" runat="server" Text="Start" OnClick="Button1_Click" />
    </div>
    </form>
</body>
 protected void Button1_Click(object sender, EventArgs e)
        {
           UpdatePanel1.Visible = true;
           ThreadClass cl = new ThreadClass();
           cl.begin();
           Timer1.Enabled = true;
        }
        protected void Timer1_Tick(object sender, EventArgs e)
        {
          if (ThreadClass.present <= 100)
          {
             Button1.Enabled = false;//if you use JQuery function above ,you may annotate it
             lbl.Text = ThreadClass.present.ToString() + "%";
             lbl.BackColor = System.Drawing.Color.Red;
             lbl.Width = ThreadClass.present * 2;
          }
          if (ThreadClass.present == 100)
          {
             ThreadClass.present = 0;
             UpdatePanel1.Visible = false;
             Button1.Enabled = true;
             Timer1.Enabled = false;
          }
        }
        public class ThreadClass
        {
            public static int present;
            public ThreadClass(){}
            public void begin()
            {
               if (present == 0)
               {
                   lock (this)
                   {
                      Thread tr = new Thread(new ThreadStart(() =>
                         {
                           for (int i = 0; i <= 1000; i++)
                           {
                              present = 100 * i / 1000;//Calculate the percentage completed  
                              Thread.Sleep(10);
                           }
                         }));
                   tr.IsBackground = true;
                   tr.Start();
                   }
               }
            }
        }

If you have any concern about it, please feel free to let me know.
Best regards,
Aswecan

Hi Aswecan,

I’m very thankful, that you posted proper script.

Javascript NaN is appearing on firefox and chrome working only on IE, function for count down time in mins and seconds

I have a javascript function, it shows release time count down in minutes and seconds. as soon as it gets triggered it is starting a count down from 30 minutes onwards, shows mins : seconds.

Working fine in IE, But on firefox and chrome, only seconds part working not minutes.

showing as 

Nan: 59

Nan: 58

minutes part is showing as not a number, can you please kindly help advise what may be the issue.

I am only guessing the part below which is BOLD texted has the issue may be with the browser. Thanks a lot for the helpful info.

function startInterval(locktime)
{
diffsec = 60;

starttime = new Date();
releasetime = new Date();
alerttime = new Date();

//sets the time the record will be released
releasetime.setMinutes(releasetime.getMinutes() + locktime);
//set the time the alert will be fired(95% of the release time)
alerttime.setTime(alerttime.getTime() + locktime*60*1000*0.05);

//calculates the difference between startlocktime and releaselocktime
diffmin = DateDiff(starttime,releasetime,"m",false);
if (isNaN(diffmin)) {
showmin = "AA"
}

//adjusts the minutes to be shown witj 2 digits
if (diffmin < 10) {
showmin = "0" + diffmin;
} else {
showmin = "" + diffmin;
}

var e1 = window.parent.frames[2].document.getElementById("txtRemainingTime")
if (e1!=null) {
e1.value = showmin + ‘:00′;
}

//calls the timer every second
interval = window.setInterval("startLockClock()",1000);
}

Hi Cplusplus,

Thanks for your post.

According to your description, my understanding is that your javascript function works fine on IE, but it don’t work as expected on firefox and chrome. The firefox and chrome are out of our support scope, so I recommend to post your problem in  firefox and
chrome forum.

Thanks for your understanding.

Best Regards,

Fei Han

Append a larger data to view after ajax post without freezing the browser.

How can I append a partial view after a ajax post? The partial view content size is 50-60 kb. So I,m using asynchronous ajax post and append that data. Now each content has only lesser than 10kb. But now I have append multiple data after every ajax success,
so browser has been hanged some interval of time(5-8 seconds) . How can I previent this?

Can any one one give suggestion this?

Hi LTAravindh,

please check that if you have set your ajax request  async as true. if it is set to false ,the browser will freeze until a response is received.

You can try the code below:

$.ajaxSetup({
    async: true
});

$.post(url,data,success,datatype);

Or you can try use $.ajax() equivalent:

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType,
  async:true
});

Best Regards,

Kevin Shen.

That depends on the RAM size of the machine the website is being viewed on, since a lot of network requests hang the browser or the computer itself. You need to make sure, that you pass each of the data, one after the other. You can send the requests and
returns true if the previous data was recieved and processed. Once true, send the next amount of data. 

This error is a user related issue, and the machine related issue. You can minimize it, using lesser executions per seconds, if you’re uploading data, don’t download. If you’re going through algorithm, pause remaining threads. Using the Threadings of the
.NET Framework would be a great thing to work around with, but that is on the server side. 

Try using a time interval of the JS framework and send data after 1 second the ajax returns true. 

https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setInterval

LTAravindh

I,m using asynchronous ajax post and append that data.

What do you mean by "append that data"? Are you generating DOM elements (table rows or divs) dynamically from JSON or similar? You might find that returning an HTML snippet instead of data and using jQuery’s load method is more efficient.

Hi Kevin,

I tried as per your suggestion. At the time of ajax post browser has not been hang. Browser will be hang when I append DOM element.

Hi Mikesdotnetting,

In my question data represented as a DOM element.

Hi LTAravindh,

I am not quite sure how much data you append to your dom element.

If you did that ,the browser will hang .

I suggest that you can dynamically create the data /table in the server side, and append the  table into the page.

Best Regards,
Kevin Shen.

[RESOLVED]Need to return full page control to aspx page after a few timer partial postbacks

I am trying to return full page control to my aspx page after performing a number of Timer control partial post backs.

What is the best way to stop the partial post backs and allow the web page to update other controls throughout the page?

Hi march,

Thanks for your post.

march11

What is the best way to stop the partial post backs and allow the web page to update other controls throughout the page?

As for your question, firstly, you could refer to this issue “How to Control or Stop Partial Post Back in Update Panel to learn how
to stop partial post back. Secondly, we could access controls by using the controls collection, you could check

"How to: Access Controls by using the Controls Collection"
to learn how to get all the controls in webpage.

If you have any question about my reply, please let me know freely.

Best Regards,

Fei Han