Core JavaScript

Timed Functions

This JavaScript example demonstrates how to use the SetTimeout() and SetInterval functions to create timed callbacks. Click the buttons to start the timed function call loops.

TimedFunctions.html

<!DOCTYPE html>
<html>
  <head>
    <title>XoaX.net's Javascript</title>
    <script type="text/javascript" src="TimedFunctions.js"></script>
		<style>
			div {
				width:200px;
				height:100px;
				border:1px solid black;
			}	
		</style>
  </head>
  <body>
  	<button onclick="StartStopTimeout()">Toggle Timeout</button>
  	<div id="idTimeout"></div>
  	<button onclick="StartStopInterval()">Toggle Interval</button>
  	<div id="idInterval"></div>
  </body>
</html>

TimedFunctions.js

// The timeout function is called once after a set time interval.
var giTimeoutID = null;
// The interval is called once for every time interval that passes. 
var giIntervalID = null;
// These ids can be used with the clear functions to stop the timeout of interval functions.

function StartStopTimeout() {
	// If the timeout is running stop it
	if (giTimeoutID != null) {
		clearTimeout(giTimeoutID);
		giTimeoutID = null;
	} else { // Otherwise, start looped calls
		// Start the loop with a single call after 1 second and set the id.
		giTimeoutID = setTimeout(TimeoutLoop, 1000, "idTimeout");
	}
}

function TimeoutLoop(sID){
	ChangeBackground(sID);
	// Call the function itself again with the id parameter after 2 seconds and set the id.
	// Since the timeout only executes once, it must be set repeatedly if it is to loop.
	giTimeoutID = setTimeout(TimeoutLoop, 2000, sID);
}

function StartStopInterval() {
	// If the interval is running stop it
	if (giIntervalID != null) {
		clearInterval(giIntervalID);
		giIntervalID = null;
	} else { // Otherwise, start looped calls
		// Call the ChangeBackground() function every 2 seconds with the id of the element.
		giIntervalID = setInterval(ChangeBackground, 2000, "idInterval");
	}
}

function ChangeBackground(sID) {
	let qElement = document.getElementById(sID);
	let iRed = Math.floor(Math.random()*256);
	let iGreen = Math.floor(Math.random()*256);
	let iBlue= Math.floor(Math.random()*256);
	let dAlpha = Math.random();
	qElement.style.backgroundColor = "rgba("+iRed+", "+iGreen+", "+iBlue+", "+dAlpha+")";
}
 

Output

 
 

© 2007–2025 XoaX.net LLC. All rights reserved.