Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a safe delay in JavaScript?

Tags:

javascript

A way that doesn't hog resources, just stops execution for 1 second then executes?

What I want to do is dynamically move a Google gauge from one value to another, creating the effect of it moving to the value instead of jumping to it.

i.e. -

for(original_value; original_value < new_value; original_value++)
{
    data.setValue(0, 1, original_value);
    delay half a second here in JavaScript?
}  

Is this an OK way of doing this or is something closer to what the demo is doing is extremely better? :
How to: Dynamically move Google Gauge?

like image 943
Greg McNulty Avatar asked Sep 18 '10 00:09

Greg McNulty


2 Answers

No. JavaScript in web browsers is not only single threaded, but it shares the same thread with the browser rendering. If your JavaScript code were to block, the browser UI would become unresponsive during that period.

The typical way to tackle time-based events in JavaScript is by using asynchronous timers. John Resig wrote an intresting article a while ago called "How JavaScript Timers Work", which you may want to check out.


UPDATE:

Are you using the Google Visualization API for the guages? If so, it seems to me that Google already handles the smooth animation that you're trying to achieve. Try the following in the Google Code Playground (keep an eye on the Network gauge):

function drawVisualization() {
  // Create and populate the data table.
  var data = new google.visualization.DataTable();
  var chart;

  data.addColumn('string', 'Label');
  data.addColumn('number', 'Value');
  data.addRows(3);
  data.setValue(0, 0, 'Memory');
  data.setValue(0, 1, 80);
  data.setValue(1, 0, 'CPU');
  data.setValue(1, 1, 55);
  data.setValue(2, 0, 'Network');
  data.setValue(2, 1, 68);

  // Change the value of the Network Gauge after 3 seconds.
  setTimeout(function () { data.setValue(2, 1, 20); chart.draw(data); }, 3000);

  // Create and draw the visualization.
  chart = new google.visualization.Gauge(document.getElementById('visualization'));
  chart.draw(data);
}
like image 162
Daniel Vassallo Avatar answered Sep 27 '22 00:09

Daniel Vassallo


This should work.

var id, value = original_value;
id = setInterval(function() {
    if (value < new_value) {
        data.setValue(0, 1, value++);
    } else {
        clearInterval(id);
    }
}, 1000);
like image 23
ChaosPandion Avatar answered Sep 27 '22 00:09

ChaosPandion