You can reRender scripts that should be run when conditions are met. I wrote up an arbitrary example where you have (approximately) a 50% chance of getting a popup dialog, and 50% chance of just plain text. Every five seconds, the server is called again, and you may get a dialog popup. This requires no user interaction.
public class showAlertRandom {
public boolean showAlert { get; set; }
public Decimal numberValue { get; set; }
public showAlertRandom() {
doRandomAlert();
}
public void doRandomAlert() {
numberValue = Math.random();
showAlert = numberValue < 0.5;
}
}
<apex:page controller="showAlertRandom" showHeader="true">
<apex:form id="form">
<apex:outputText rendered="{!showAlert}" id="alert">
<script>
alert('Hello World');
</script>
</apex:outputText>
<apex:outputText rendered="{!not showAlert}" id="noAlert">
No alert this time, sorry. Random value was: {!numberValue}.
</apex:outputText>
<apex:actionPoller interval="5" action="{!doRandomAlert}" reRender="form" />
</apex:form>
</apex:page>
How it works:
Though Apex Code can't call JavaScript directly, it can set a variable to render a script block that can run arbitrary code. On each render, when the variable is true, an alert is produced. I wouldn't try doing this inside a closure or the middle of a script block, as you'll probably get very unpredictable results. You could dispatch a custom event or call some global function, if you prefer. You can use this technique anywhere reRender is supported, such as on a commandLink, commandButton, and actionFunction.
oncomplete
event of your apex tag, but knowing when the variable has become a value will require using a re-render to update the page's DOM, then a query selector to find the updated value. There is no direct way for Apex (server side) to invoke javascript (client side) and pass it a value.