Griffiths web design based in Royston, Hertfordshire, United Kingdom


Exploring JavaScript’s setTimeout and setInterval methods – Example’s and Explanations.

Author:   Michael Griffiths

Date created:   22 July 2016

[postpic=stopwatch.jpg class=img-responsive title=settimeout-vs-etinterval alt=set timeout and set interval style=STYLE][/postpic] [l]I would like to discuss with you today JavaScript’s setTimeout and setInterval methods. I will attempt to explain them and I will also be providing some examples. To follow along with the examples you won’t need much prior knowledge as all the JavaScript code will be explained and all HTML and CSS will also be provided and given limited explanation.[/l] [hdmd]setTimeout vs setInterval – the difference.[/hdmd] [l]One thing that many newcomers to JavaScript get mixed up is when to use setTimeout and when to use setInterval.[/l] [l]The key thing to remember is that setTimeout executes the function once when the timer runs out. Whereas setInterval executes the function when the timer runs out but then restarts the timer and loops continuously until clearInterval() is called.[/l] [hdmd]setTimeout[/hdmd] [l]I would like to start with setTimeout[/l] [hdsm]The syntax[/hdsm] [code] var timerOne = setTimeout(function|code, delay);[/code] [def] [term]Function | code[/term] [desc]The function or piece of code you wish to execute when the timer runs out. [/desc] [term]Delay[/term] [desc]How long you wish to wait before executing the function or code previously specified. Please note that time is counted in milliseconds. [/desc][/def] [l][b]An example:[/b][/l] [code] [/code] [l]This code will execute an alert after 5 seconds which will read ‘hello’. We wrapped our alert in a function declaration. This is not always necessary, as you will see from the next example you can also use functions that have already been declared elsewhere.[/l] [code] function exOne() { var timerOne = setTimeout(trythis, 5000); } function trythis() { alert("hello"); } [/code] [l]In this example we performed exactly the same task except we put our alert in a function then called that function from within the setTimeout method. In this example I have omitted the html as that has remained unchanged from the previous example. Calling an alert on a time delay may not seem all that useful out in the real world but the principle remains the same no matter the complexity of the function being called. In the interest of providing a more usable real world-ish example we will be creating a div which will have different css classes applied to it which will change the colour of the div we will also update the label text. It will cycle through three different colours after a set amount of time. [/l] [l]First of all we will add some HTML.[/l] [code]

[/code] [l]As you can see all we need is a div, a label to contain the text and a button to start the process. In the ‘onclick’ event declaration of the button you will see ‘StartTimer()’, this is the name of the function we will be creating in our JavaScript. This function is where the magic is.[/l] [l]Next we need to add some CSS.[/l] [code] #traffLight{ border-radius:100px; width:200px; height:200px; margin:0 auto; } #status{ position:relative; top:50%; display:block; margin-left:auto; margin-right:auto; text-align:center; color:#808080; } .red{ background:#ff0000; } .yellow{ background:#ffd800; } .green{ background:#00ff21; } [/code] [l]First we made the div a circle by using the border-radius property. We set the border radius to half the height of the div which makes the div a circle shape. We also set the height and width of the div and we centred the div. Next we set some styles on the label. We set its position to relative so that its position is relative to its containing div. we also centred it vertically and horizontally, centre aligned the text and we set the colour of the text. Finally we created 3 classes: red, yellow and green. These classes will be responsible for changing the background colour of the div.[/l] [l]Now we have the CSS in place it’s time to bring it all to life with some simple JavaScript.[/] [code] function StartTimer() { var traffLight = document.getElementById("traffLight"); var status = document.getElementById("status"); if (traffLight.className === "red") { traffLight.className = "yellow"; status.innerText = "Ready?"; window.setTimeout(StartTimer, 3000); } else if (traffLight.className === "yellow") { traffLight.className = "green"; status.innerText = "Start!"; window.setTimeout(StartTimer, 12000); } else { traffLight.className = "red"; status.innerText = "Stop!"; } } [/code] [l]That is all there is to it, just that one tiny function. First we searched the DOM for our div and our label, we stored them in variables. Next we check which of our colour classes is already in place on the div. Once the correct class name has been found the code overwrites it with a new class, i.e. if the class already present was red then it overwrites it with yellow. Our code then updates the text of the label. In the next line of code we call window.setTimeout(). Within that method we feed it 2 parameters, one is the function to be called when the time runs out and the second parameter is how long to wait before calling the function. Please note time is counted in milliseconds. If you run the page in your web browser you’ll see that the circle starts out life red. When you click the button it then turns to yellow for 3 seconds then changes to green for 12 seconds and finally change back to red. As you can see from this example setTimeout only executes the function once, and only when the timer has depleted.[/l] [hdmd]setInterval[/hdmd] [hdsm]The syntax[/hdsm] [code] var intervalOne = setInterval(function|code, delay);[/code] [def] [term]Function | code [/term] [desc]The function or piece of code you wish to execute when the timer runs out.[/desc] [term]Delay[/term] [desc]How often you wish to wait before executing the function or code previously specified. Please note that time is counted in milliseconds.[/desc][/def] [l][b]An example:[/b][/l] [l]First a little bit of html.[/l] [code]


[/code] [l]We have created 2 buttons and a set of paragraph tags. Nothing fancy here![/l] [l]Now we need to add some JavaScript:[/l] [code]var int01; function exTwo() { var text = document.getElementById("textHolder"); int01 = setInterval(function () { text.innerText += "hello "; }, 3000); } function endExTwo() { clearInterval(int01); } [/code] [l]In this code we have created a variable which will hold our setInterval method. Next we created two functions; the first function finds our p element, once it has done that it add the word hello to our p element. It does this every 3 seconds. In our second function we call the clearInterval method to cancel the execution of our setInterval method. The clearInterval methods takes one parameter, which in this case is the name of the variable that contains our set interval method.[/l] [l]Now we will go through one more example. Remember the traffic light effect from our set timeout method example? We will be creating something similar to this, but not quite identical. I will show you the HTML and the JavaScript but you can use the CSS from our setTimout example.[/l] [l]The html:[/l] [code]

Traffic light effect demo

[/code] [l]As you can see the HTML is almost the same as the HTML we used in the setTimeout example, except in this HTML we call our function on the body tags onload event. This means our code will run as soon as the page is loaded, therefore eliminating the need for a button.[l] [l]Now we can move on to our JavaScript:[/l] [code] function loadTraffLight() { var traffLight = document.getElementById("traffLight"); var status = document.getElementById("status"); var timer; timer = setInterval(function () { if (traffLight.className === "red") { traffLight.className = "yellow"; status.innerText = "O.K"; } else if (traffLight.className === "yellow") { traffLight.className = "green"; status.innerText = "Authorised"; } else { traffLight.className = "red"; status.innerText = "Stop Working"; } }, 1000); } [/code] [l]First we find our div and our label and store them in variables. We also create a variable which will hold our set interval method. Next we call the setInterval method. The function parameter of the setInterval method checks to see which class name is currently attached to the div and then updates accordingly. This will continue to loop like this forever. To stop the loop you will need to call clearInterval as previously discussed.[/l] [l]Now you are an expert in the use of setInterval and setTimeout. Both methods have their merits and are extremely common place in the world of front end web development. I hope you found this guide to be helpful. If you have any comments or questions then please do not hesitate to leave a comment below or get in touch via the contact page of my site [/l]

About the author

My name is Michael Griffiths, I am a website designer and developer and the owner of Griffiths Web Design. I am based in Royston, Hertfordshire. Most of my work is local, Hertfordshire, Cambridgeshire, Bedfordshire, Essex etc. but that’s not to say I won’t work elsewhere. One of the wonders of modern technology is remote working. So no matter where the client is located it is always possible to connect.

I specialise in creating ASP.NET webforms applications using C#. I use Microsoft SQL Server for database development and on the front end I use Html, CSS and JavaScript. I am also proficient in the use of jQuery and several CSS frameworks.

One of my greatest passions in life is learning. Which is why I chose to pursue a career in web design and development, technology is in a state of constant and rapid evolution which means there is always something new to learn. I also enjoy writing, both fiction and non-fiction.


Please feel free to leave a comment below:







Griffiths Web Design Logo by Michael Griffiths
Griffiths Web Design Logo by Michael Griffiths