Skip to content

Instantly share code, notes, and snippets.

@mmoravec
Created May 10, 2016 22:35
Show Gist options
  • Save mmoravec/4fc186b6fb81119949939aa314294afd to your computer and use it in GitHub Desktop.
Save mmoravec/4fc186b6fb81119949939aa314294afd to your computer and use it in GitHub Desktop.
// if logic to prevent experiment from running on itself in the editor.
if (window.location.search.match(/\d/g).join("") !== 5450482367) {
(function() {
'use strict';
var experiment_id = window.location.search.match(/\d/g).join("");
var current_timestamp;
var next_timestamp;
var _$;
// Wait for jQuery to be enabled on the page.
window.jQueryEnabledInterval = setInterval(function() {
if (_$.fn.jquery === "1.7.2") {
_$ = window.$;
findInitialTimeStamps();
checkForInternalSave();
clearInterval(window.jQueryEnabledInterval);
}
}, 50);
// Retrieve initial timestamps.
function findInitialTimeStamps() {
_$.get("https://app.optimizely.com/api/v1/experiments/" + experiment_id, function(response) {
current_timestamp = new Date(response.last_modified);
next_timestamp = new Date(response.last_modified);
});
recursiveCheck($);
}
// Use ajaxComplete to check for internal saves and update timestamp accordingly.
function checkForInternalSave() {
_$(document).ajaxComplete(function(event, response, settings) {
// if any of these endpoints are pinged, then we need to update the timestamp since it's an internal save.
if (settings.url === "/experiment/save") {
current_timestamp = JSON.parse(response.responseText).last_modified;
next_timestamp = JSON.parse(response.responseText).last_modified;
// Events captured: Start, Pause, Goals and Audiences are loaded asynchronously and are much less prone to concurrency issues.
} else if (settings.url === "/tool/experiment/pause" || settings.url === "/tool/experiment/start") {
_$.get("https://app.optimizely.com/api/v1/experiments/" + experiment_id, function(response) {
current_timestamp = new Date(response.last_modified);
next_timestamp = new Date(response.last_modified);
});
}
});
}
function recursiveCheck() {
window.checkTimestampInterval = setInterval(function() {
_$.get("https://app.optimizely.com/api/v1/experiments/" + experiment_id, function(response) {
next_timestamp = new Date(response.last_modified);
if (current_timestamp < next_timestamp) {
$('#last-saved-container').html("WARNING! Saving might overwrite someone else's work since this experiment was saved recently!<br>Copy your work and refresh the page.");
$('#last-saved-container').removeClass('muted');
$('#last-saved-container').attr("style", "color: #de5959; !important");
$('#last-saved-container').css({"position":"relative", "top":-2});
$('.lego-button-group:eq(1)').css({"position":"relative", "top":-4});
clearInterval(window.checkTimestampInterval);
}
});
}, 3000);
}
})();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment