3. Making the Clock Efficient

Just like all content types in Yodeck, Widgets are pre-loaded during playback. This means that it may take several seconds (or even minutes) between loading the Widget instance on the Player’s Web Viewer, and actually getting the Widget to show on the screen.

This has two effects:

  • If your Widget is not static (e.g. you show a playlist of images), then you need to know when your Widget is displayed, so that you can start your sequence.
  • If your Widget is resource-heavy, then you are wasting Player resources that could result in a bad playback experience.

In the “Simple Clock” case, none of the above applies, but let’s say that you wanted to start the clock once the Widget is shown, and stop the clock once the Widget is hidden.

Modify the Widget code as follows:

index.html

<!DOCTYPE html>
<html>
<head>
<script>

var use_seconds = true;

function startTime() {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = 0
    m = checkTime(m);
	txtEl = document.getElementById('txt')

	if (use_seconds) {
		s = today.getSeconds();
    	s = checkTime(s);
		txtEl.innerHTML = h + ":" + m + ":" + s;
	}
	else {
    	txtEl.innerHTML = h + ":" + m;
	}
    window.t = setTimeout(startTime, 500);
}


function checkTime(i) {
    if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
    return i;
}

function init_widget(config) {
		if (!config) {
			return;
		}	
		if("clock_font_size" in config){
			var pixels = config.clock_font_size + "px"
			document.getElementById('txt').style.fontSize = pixels;
		}
		if("use_seconds" in config){
			use_seconds = config.use_seconds;
		}
}

function start_widget(){
	startTime()
}

function stop_widget(){
	if(window.t){
		clearTimeout(window.t);
	}
}

</script>
</head>

<body>

<div id="txt" style="font-size: 48px"></div>

</body>
</html>

Modifications explained

As you can see, we now do not start the clock on page load, and we added two functions:

  • The start_widget function is called just before the Widget is shown on screen. At that point, we start our clock.
  • The stop_widget function is called just after the Widget is removed from the screen. At that point, we stop our clock.

The second call is not really necessary in our case, since the Web Viewer will terminate and all resources will be freed, but it is good to know. Some Widgets require finalization calls to backend services in order to save their state.