THIS IS NOT A DUPLICATE! I have a piece of JavaScript with what I call a &quot;nested&quot; setInterval; one setInterval that calls a function with another setInterval. What i want is when the &quot;outer&quot; setInterval calls the function when the &quot;inner&quot; setInterval is already running, I want the &quot;inner&quot; setInterval to stop it's original interval and start again fresh. So:  Outer setInterval fires. Outer setInterval calls function with inner setInterval. Inner setInterval fires.  ... inner runs for a while  Outer setInterval fires ... again. Outer setInterval calls inner setInterval ... again Inner setInterval stops it's original run. Inner setInterval starts a fresh, new run.  See my example below:       &lt;!DOCTYPE html&gt;     &lt;html&gt;         &lt;head&gt;             &lt;title&gt;&lt;/title&gt;             &lt;style type="text/css"&gt;                 div {                     margin: 100px 100px;                 }             &lt;/style&gt;             &lt;script type="text/javascript"&gt;                      let alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];                      function start(){                     var the_button = document.getElementById('the_button');                     the_button.addEventListener('click', testFunction);                 }                      function testFunction(){                     console.log("Starting ...");                     if(myIntervalVal) clearInterval(myIntervalVal);                     var myIntervalVal = setInterval(printAlphabet, 10000);                 }                      function printAlphabet(){                     var i = 0;                     console.log(alphabet[i]);                     if(mySubInterval) clearInterval(mySubInterval);                     var mySubInterval = setInterval(function(){                         i++;                         if(i === alphabet.length) i = 0;                         console.log(alphabet[i]);                     }, 1000);                 }             &lt;/script&gt;         &lt;/head&gt;         &lt;body onload="start();"&gt;&lt;div&gt;&lt;button type="button" id="the_button"&gt;click me&lt;/button&gt;&lt;/div&gt;&lt;/body&gt;     &lt;/html&gt;    The way I feel this should work is: outer fires     inner prints     A     B     C     D     E     F outer is fired again     inner stops printing     inner prints     A     B     C     D     E     F     ...  Is this not possible?
122
What is the scope of variables in javascript? Do they have the same scope inside as opposed to outside a function? Or does it even matter? Also, where are the variables stored if they are defined globally?
4059
The situation is somewhat like-  var someVar = some_other_function(); someObj.addEventListener("click", function(){     some_function(someVar); }, false);   The problem is that the value of someVar is not visible inside the listener function of the addEventListener, where it is probably being treated as a new variable.
42370
What is the most recommended/best way to stop multiple instances of a setTimeout function from being created (in javascript)?  An example (psuedo code):  function mouseClick() {    moveDiv("div_0001", mouseX, mouseY); }  function moveDiv(objID, destX, destY) {    //some code that moves the div closer to destination    ...    ...    ...     setTimeout("moveDiv(objID, destX, destY)", 1000);    ...    ...    ... }   My issue is that if the user clicks the mouse multiple times, I have multiple instances of moveDiv() getting called.  The option I have seen is to create a flag, that only allows the timeout to be called if no other instance is available...is that the best way to go?  I hope that makes it clear....
108043
I'm seeing some unexpected behaviour with the locker service enabled when updating two fields on an object, one of which is nested inside a sub-object.   I have a lightning application that initialises a JavaScript object and passes references to fields on the object, and the object itself, as attributes to a contained component:  App Markup  &lt;aura:application &gt;     &lt;aura:attribute name="obj" type="object" /&gt;     &lt;aura:handler name="init" value="{!this}" action="{!c.init}" /&gt;      Top level value: &lt;ui:outputText value="{!v.obj.value1}" /&gt; &lt;br/&gt;     Nested value: &lt;ui:outputText value="{!v.obj.sub.value2}" /&gt; &lt;br/&gt;      &lt;c:MultiFieldTest obj="{!v.obj}" value1="{!v.obj.value1}" value2="{!v.obj.sub.value2}" /&gt;      &lt;br/&gt;      &lt;button onclick="{!c.showObj}"&gt;Show Object&lt;/button&gt; &lt;/aura:application&gt;   app controller  ({     init : function(component, event, helper) {         helper.init(component);     },     showObj : function(component, event, helper) {         helper.showObj(component);     } })   app helper:  ({     init : function(cmp) {         var obj={value1:'', sub:{value2:''}};         cmp.set('v.obj', obj);     },     showObj : function(cmp) {         alert('Object = ' + JSON.stringify(cmp.get('v.obj')));     } })   So the concept is there is an object with the structure:  {value1:'',   sub:{      value2:''} }   and I want to pass value1 and sub.value2 as attributes to a component that will update them. However, to ensure that the changes are propagated up and down the food chain (as per : ) I am also passing in the object itself. Essentially I want the contained component to update a couple of fields and propagate the changes without having to know which fields it is updating.  The containing component markup:  &lt;aura:component&gt;     &lt;aura:attribute name="value1" type="String" /&gt;     &lt;aura:attribute name="value2" type="String" /&gt;     &lt;aura:attribute name="obj" type="object"/&gt;      &lt;button onclick="{!c.setValues}"&gt;Set Values&lt;/button&gt;  &lt;/aura:component&gt;   controller:  ({     setValues : function(component, event, helper) {         helper.setValues(component);     } })   helper:  ({     setValues : function(cmp) {         var obj=cmp.get('v.obj');         console.log('Obj before = ' + JSON.stringify(obj));          cmp.set('v.value1', 'Value 1');         cmp.set('v.value2', 'Value 2');           obj=cmp.get('v.obj');         console.log('Obj after = ' + JSON.stringify(obj));          cmp.set('v.obj', obj);     } })   So when the user clicks the button, strings are set into the value1/value2 attributes and the underlying object 'reset' into the page. I then click on the 'Show Object' button, and the results are as expected with the locker service deactivated.   However, when I activate the locker service, only the second update 'sticks' and obj.value1 is empty, although both ui:outputText elements show the value1/value2 details as expected. What appears to be happening is that setting the first attribute updates the page as expected, and the object, but setting the second attribute updates the page and an earlier version of the object, minus the value1 details.  However, if I don't get the obj attribute at the beginning of the setValues method, it works:  setValues : function(cmp) {     // var obj=cmp.get('v.obj'); &lt;---- removed this      cmp.set('v.value1', 'Value 1');     cmp.set('v.value2', 'Value 2');       var obj=cmp.get('v.obj');     console.log('Obj after = ' + JSON.stringify(obj));      cmp.set('v.obj', obj); }   So pretty easy to work around, but I'm curious as to why this would be necessary with the locker service enabled - there's no secure versions of anything in play and the attributes are all accessible to the component. Its almost like the act of looking at the object fixes a version somewhere, and all updates retrieve that version before applying their update, rather than retrieving the latest version.
100032
How exactly do you make an auto-refreshing div with JavaScript (specifically, jQuery)?  I know about the setTimeout method, but is it really a good practice ? Is there a better method?  function update() {     $.get("response.php", function(data) {         $("#some_div").html(data);     });     window.setTimeout("update();", 10000); }
1554
I need to warn users about unsaved changes before they leave a page (a pretty common problem). window.onbeforeunload = handler  This works but it raises a default dialog with an irritating standard message that wraps my own text. I need to either completely replace the standard message, so my text is clear, or (even better) replace the entire dialog with a modal dialog using jQuery. So far I have failed and I haven't found anyone else who seems to have an answer. Is it even possible? Javascript in my page: &lt;script type=&quot;text/javascript&quot;&gt;        window.onbeforeunload = closeIt; &lt;/script&gt;  The closeIt() function: function closeIt() {   if (changes == &quot;true&quot; || files == &quot;true&quot;)   {       return &quot;Here you can append a custom message to the default dialog.&quot;;   } }  Using jQuery and jqModal I have tried this kind of thing (using a custom confirm dialog): $(window).beforeunload(function () {     confirm('new message: ' + this.href + ' !', this.href);     return false; });  which also doesn't work - I cannot seem to bind to the beforeunload event.
17026
I have a JavaScript widget which provides standard extension points. One of them is the beforecreate function. It should return false to prevent an item from being created.   I've added an Ajax call into this function using jQuery:  beforecreate: function (node, targetNode, type, to) {   jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),    function (result) {     if (result.isOk == false)          alert(result.message);   }); }   But I want to prevent my widget from creating the item, so I should return false in the mother-function, not in the callback. Is there a way to perform a synchronous AJAX request using jQuery or any other in-browser API?
42411
How to check whether a JavaScript variable defined in cross-browser way?  I ran into this problem when writing some JavaScript utilizing FireBug logging. I wrote some code like below:  function profileRun(f) {     // f: functions to be profiled     console.profile(f.constructor);     f();     console.profileEnd(f.constructor); }   It works fine in FireFox/FireBug, but it reports error in IE8 RC1. So, I'd like to do some checking whether console variable exists in the execution environment.  Below code works fine in FireFox, but not in IE8 RC1.   function profileRun(f) {     if (console != undefined) {         console.profile(f.constructor);     }      f();      if (console != undefined) {         console.profileEnd(f.constructor);     } }   However, if I do it this way. It works in IE8 RC1. Why?   function profileRun(f) {     if (window.console != undefined) {         console.profile(f.constructor);     }      f();      if (window.console != undefined) {         console.profileEnd(f.constructor);     } }   Is there any cross-browser way to check it?
21847
Given a function:  function x(arg) { return 30; }   You can call it two ways:  result = x(4); result = new x(4);   The first returns 30, the second returns an object.  How can you detect which way the function was called inside the function itself?  Whatever your solution is, it must work with the following invocation as well:  var Z = new x();  Z.lolol = x;  Z.lolol();   All the solutions currently think the Z.lolol() is calling it as a constructor.
4181
What's the best way to break from nested loops in Javascript?  //Write the links to the page. for (var x = 0; x &lt; Args.length; x++) {    for (var Heading in Navigation.Headings)    {       for (var Item in Navigation.Headings[Heading])       {          if (Args[x] == Navigation.Headings[Heading][Item].Name)          {             document.write("&lt;a href=\""                 + Navigation.Headings[Heading][Item].URL + "\"&gt;"                 + Navigation.Headings[Heading][Item].Name + "&lt;/a&gt; : ");             break; // &lt;---HERE, I need to break out of two loops.          }       }    } }
23614
This question has bugged me for a while. I want to write a nested function, f(g(x)). If I naively enter it:  \begin{align}     f(g(x))=y \end{align}     The problem is that each and every parenthesis is the same size as all of the others. Shouldn't the outer parentheses be larger? But if I do this:  \begin{align}     f\left(g(x)\right)=y \end{align}     Now it looks even less like the functions are nested. What's the proper way to do this?
110293
I am trying to work out what script is required to have multiple timestamps on several tabs however each one I have tried doesn't work for me.  I am new to this. When text is added to column 2 I need a timestamp in column 1.  When text added in 8 I need a timestamp in 7.  When 15 which is a checkbox, a timestamp in 16, and when 18, timestamp in 17.  Is this possible to have so many? My current script is as follows and this is giving me the time stamp in column 1 when column 2 is amended and it doesnt overwrite when it is changed a second time. function onEdit(e) {   var row = e.range.getRow();   var col = e.range.getColumn();   if (col === 2 &amp;&amp; row &gt; 1 &amp;&amp; e.source.getActiveSheet().getName() === &quot;June 2021&quot;) {     if (e.source.getActiveSheet().getRange(row, 1).getValue() == &quot;&quot;) {       e.source.getActiveSheet().getRange(row, 1).setValue(new Date());     }   } }
59846
In the following example code, I attach an onclick event handler to the span containing the text "foo". The handler is an anonymous function that pops up an alert().  However, if I assign to the parent node's innerHTML, this onclick event handler gets destroyed - clicking "foo" fails to pop up the alert box.  Is this fixable?  &lt;html&gt;  &lt;head&gt;  &lt;script type="text/javascript"&gt;    function start () {     myspan = document.getElementById("myspan");     myspan.onclick = function() { alert ("hi"); };      mydiv = document.getElementById("mydiv");     mydiv.innerHTML += "bar";   }   &lt;/script&gt;  &lt;/head&gt;   &lt;body onload="start()"&gt;    &lt;div id="mydiv" style="border: solid red 2px"&gt;      &lt;span id="myspan"&gt;foo&lt;/span&gt;    &lt;/div&gt;  &lt;/body&gt;  &lt;/html&gt;
14541
I have a pretty good understanding of Javascript, except that I can't figure out a nice way to set the "this" variable.  Consider:  var myFunction = function(){     alert(this.foo_variable); }  var someObj = document.body; //using body as example object someObj.foo_variable = "hi"; //set foo_variable so it alerts  var old_fn = someObj.fn;   //store old value someObj.fn = myFunction;   //bind to someObj so "this" keyword works someObj.fn();               someObj.fn = old_fn;       //restore old value   Is there a way to do this without the last 4 lines?  It's rather annoying...  I've tried   binding an anonymous function, which I thought was beautiful and clever, but to no avail:  var myFunction = function(){     alert(this.foo_variable); }  var someObj = document.body;        //using body as example object someObj.foo_variable = "hi";        //set foo_variable so it alerts someObj.(function(){ fn(); })();    //fail.   Obviously, passing the variable into myFunction is an option... but that's not the point of this question.  Thanks.
48930
I read about Drupal behaviors today, and I tried writing the following code.  (function ($) {    Drupal.behaviors.mymodule = {     attach: function (context, settings) {       $('#mymodule_id', context).change(function () {         alert('Handler for .change() called.');       });     }   };  }(jQuery));    Is Drupal.behaviors.mymodule the namespace? What are the context and settings parameters passed to the Drupal behavior? Is this the equivalent of document.ready()?   Can I attach any number of functions?  Can I define JavaScript functions which will be called somewhere?
75034
I have an input form that lets me select from multiple options, and do something when the user changes the selection. Eg,  &lt;select onChange="javascript:doSomething();"&gt;   &lt;option&gt;A&lt;/option&gt;   &lt;option&gt;B&lt;/option&gt;   &lt;option&gt;C&lt;/option&gt; &lt;/select&gt;   Now, doSomething() only gets triggered when the selection changes.  I want to trigger doSomething() when the user selects any option, possibly the same one again.  I have tried using an "onClick" handler, but that gets triggered before the user starts the selection process.  So, is there a way to trigger a function on every select by the user?  Update:  The answer suggested by Darryl seemed to work, but it doesn't work consistently. Sometimes the event gets triggered as soon as user clicks the drop-down menu, even before the user has finished the selection process!
56204
I am more used to the Javascript style event handlers,  but is there a similar thing in applescript that listens to system events like logout or shutdown to execute code  or is there a way to have an applescript run on shutdown or logout?  I know about  but I would rather have something free.  All my script does is mute the volume for the next startup.