I have the following code:
function Notification(type)
{
switch (type)
{
case "success":
notificationID="not1";
break;
case "error":
notificationID="not2";
break;
}
setNotificationTimeoutId = setTimeout(function () {
jQuery('#' + notificationID).fadeOut(200, function () {
var notification = document.getElementById(notificationID);
if (notification)
{
jQuery(notification.parentNode).remove();
if (type == "success")
DoSomething();
}
setNotificationTimeoutId = null;
});
}, 5000);
}
My question is, if the function(Notification) gets called on a click event, and if it gets called two times(first with Notification(“success”) then with Notification(“error”)) by two click events, is it possible that the second function call changes the type variables value for the first function call?
For example: when the first call(one with success) enters the function inside the setTimeout(a second call to Notification already been made with type = “error”) it sees the variable ‘type’ as “error” even though this call was the first and it wass called with type = “success”?
No. The
typevariable is a parameter and therefore scope-bound to your function. It’s value won’t change in subsequent calls, every function call creates a new instance of this variable and has no access to others.Your anonymous function for the timeout has a scope which is a “subscope” of
Notification‘s one, so it will always access the righttypevariable.But your
notificationIDis a global variable (not local-scoped), and the same variable instance will be used by all calls toNotificationand from all timeouts. So it will happen that the second call toNotificationchanges it before the timeout from the first accesses it. To fix this, add thevarkeyword.Or, as
setNotificationTimeoutIdis also in an outer scope and can be accessed from both calls, you could (should?) clear any active timeouts before creating the new one, by adding the following line: