JavaScript Threading - Part 1 (Timers)

December 18, 2012 by 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(
		var time = new Date().toLocaleTimeString();
		$('#currentTime').html(time); // assuming you're using jQuery
	}, 1000

Note that the value returned by this function can be used to stop the timer using the clearInterval function, e.g. "clearInterval(timer)".

It's also prudent to point out that our callback will automatically get re-executed irrespective of when/if the previous callback finished executing, so take care when putting code in your callback that can potentially exceed your interval, which brings me to our next timer function - setTimeout.

The setTimeout function has the exact same arguments as the setInterval function, the only difference however is that this function doesn't automatically continuously call its callback - which gives us a bit more control over our timer.

In the following snippet we use the setTimeout function to populate a div on our page via an ajax request (using jQuery).

<div id="results"></div>
<script type="text/javascript">
	function GetResults() 
		var timeout = 1000;	// 1 second
				url: 'http://cstruter.localhost/tests/timers/results.php',
				cache: false
		).done(function(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	

You'll notice that we only set our delayed callback as soon as we had a succesful response back from our server, when something goes wrong with our response, we prompt the user to try again.

Note that like the setInterval function, we've got a function to stop our setTimeout as well - clearTimeout.

Now in the beginning of this post I mentioned that these functions are actually pseudo-threaded in that it runs on the same thread. To demonstrate the problem with this (from a threading perspective) you need to run the following snippet along with snippet 1.

	function ()
		var j = 0;
		for (var i = 0; i < 1000000000; i++) { j++; } // simulate some intensive work
	}, 1000);

You will notice that now instead of getting a nice smooth time ticker, the ticker starts to lag behind a bit, skipping seconds. Which is obviously not the ideal behavior we're looking for but obvious seeing that we're doing everything on one thread.

Wouldn't it be nice if we could put the problem function in its own isolated thread? Leaving the UI thread open for all things UI?

In the next part we're going to have a look at doing exactly that using web workers.

Leave a Comment

Related Posts

JavaScript Threading - Part 2 (Worker)

December 18, 2012

Latest Posts

Dependency Injection using Ninject and PostSharp

April 26, 2016

Aspect Orientated Programming (AOP) - A Brief look at PostSharp

April 15, 2016

How to become a better programmer.

April 5, 2016

JavaScript Fundamentals - Hoisting

March 22, 2016

Quick and dirty look at ECMAScript 6

March 17, 2016

JavaScript Promises

March 9, 2016

CSS Combinators

March 7, 2016

Shingles Awareness

March 4, 2016

Google Analytics : Measurement Protocol

February 24, 2016

Interesting JavaScript - SQLite (sql.js)

February 18, 2016

Most Commented on Posts

Moving items between listboxes in example

Move items between two listboxes in, VB.NET) and PHP
June 12, 2008

Simple WYSIWYG Editor

Creating a WYSIWYG textbox for your website is actually quite simple.
February 1, 2007

C# YouTube : Google API

Post on how to integrate with YouTube using the Google Data API
March 12, 2011

Populate a TreeView Control C#

Populate a TreeView control in a windows application.
August 27, 2009

ASP.NET(C#) : Autocomplete TextBox - Part 1 (From Scratch)

Part one of how to create an autocomplete textbox using ASP.NET(C#)
March 27, 2011

Angular   Architecture   ASP.NET   Astronomy   Breaking News   C#   C++   Coding Horrors   Comedy   Cross Browser   CSS   Design Patterns   ES6   Google API   IIS   Integration   JavaScript   Jquery Mobile   Love and War   Microsoft Office   Ninject   Personal   PHP   PostSharp   SEO   South Africa   SQL   Threading   TypeScript   Visual Basic   XML