December 18, 2012 by Christoff Truter JavaScript Threading
In the first part of this series we're going to have a look at timers (setTimeout and setInterval functions).
Technically these functions are actually pseudo-threaded (looks like a dog, smells like a dog, barks like a dog, humps like a dog, not a dog) - they don't spawn new threads, but instead they cleverly get executed/queued on a single thread (along with other asynchronous events).
The first function we're going to look at is the setInterval function. This function accepts three arguments, of which the first one is a callback, the second an interval (in milliseconds) of when the callback will be executed.
The third argument is optional and sets the language (of the callback script I guess ?) - I've personally never used this argument, and can't see why any sane person would want to, can somebody enlighten us ? My guess is it's got something to do with the client-side vbscript days, allowing one to mix vbscript and JavaScript in Internet Explorer (puuuuukkkke) ?
In the following snippet we use the setInterval function to display the current time and update it every second (a basic time ticker).
<div id="currentTime"></div> <script type="text/javascript"> var timer = setInterval( function() { var time = new Date().toLocaleTimeString(); $('#currentTime').html(time); // assuming you're using jQuery }, 1000 ); </script>
<div id="results"></div> <script type="text/javascript"> function GetResults() { var timeout = 1000; // 1 second $.ajax( { url: 'http://cstruter.localhost/tests/timers/results.php', cache: false } ).done(function(data) { $('#results').html(data); setTimeout(GetResults, timeout); // only call the function again once we're done }).fail(function(jqXHR, textStatus, errorThrown) { if (confirm("Error sending request, try again?")) { setTimeout(GetResults, timeout); // try call the function again } }); } GetResults(); </script>
setInterval( function () { var j = 0; for (var i = 0; i < 1000000000; i++) { j++; } // simulate some intensive work }, 1000);