Question

So I am trying to setup a timer to hide some overlays at work. This is a super basic timer, but the timer never starts or runs....I am not really sure what am I missing here. http://jsfiddle.net/deadlychambers/sEn7X/

JavaScript

$(document).ready(function () {
  CreateFrameTimer("timey", 30);
});
var FrameTimer;
var FrameTimerTotalSeconds;
var FrameTimerOn = false;

function CreateFrameTimer(TimerId, Time) {
    FrameTimerOn = true;
    FrameTimer = document.getElementById(TimerId);
    FrameTimerTotalSeconds = Time;
    UpdateFrameTimer();
    window.setTimeout("TickTock();", 1000);
}
function TickTock() {
    FrameTimerTotalSeconds -= 1;
    UpdateFrameTimer();
    if (FrameTimerTotalSeconds <= 0 || FrameTimerOn == false)
    {
        this.HideFrameOverlays();
        return;
    }
    window.setTimeout("TickTock();", 1000);
}
function UpdateFrameTimer(){
  $("#me").html(FrameTimerTotalSeconds);
}

HTML

<div id="me"></div>
Was it helpful?

Solution

window.setTimeout(TickTock, 1000); is the correct line. See Updated JSFiddle.

The JSFiddle also changes to Javascript loading to onDomReady which allows the Javascript pane to function on a global level. There's a similar SO answer which helps decipher the reason for changing that first parameter from a string to the function reference.

OTHER TIPS

There are two separate things to understand here. First, when you pass a string to setTimeout that code is simply executed in the global context. When you pass it a reference to a function, then that specific function is executed in the global context.

Second, jsfiddle allows you to choose whether your code is wrapped in another function, which determines whether your variables and functions are global.

Therefore:

  • As your code is written, the fiddle is trying to execute a global function called TickTock but no such function exists (because you've instructed jsfiddle to wrap your code in another function and JavaScript variables are scoped to their nearest containing function). So, passing a reference to the particular function you want to execute works.

  • On the other hand, you can also fix your problem by selecting one of the "no wrap" jsfiddle options, which makes your functions global and as a side-effect causes the code you pass to setTimeout to succeed.

Fixing the issue is one thing, but it's better to understand why it's happening.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top