0

I'm a novice with javascript but can usually make due. In this case, I'm having a problem with the first portion of the code submitting before executing the next portion of the code. The idea is to trigger a click, wait 5 seconds, then trigger a click on the next element in the list. If I run these individually, one at a time, it works without issue. If I run these together it is as if the first click doesn't even happen. I'm working to simulate some clicks on a MicroStrategy Dossier. Once this is working, I'll iterate through all of the div items dynamically by counting the elements first.

Any help/advice is appreciated.

var t1 = new Date();
var t2 = new Date();
var dif = 0;

//Click first element in the list
var n = "div.item[idx=\"0\"]";
$('div.scroll-container.mstrmojo-scrollNode').find(n).each(function(){
        $(this).trigger('click');   
            });

//wait  5 seconds
t2 = new Date();
        dif = t1.getTime() - t2.getTime();
            while(dif < 5000){
                t2 = new Date();
                dif = t2.getTime() - t1.getTime();  
            };

//Click second element in the list
var n = "div.item[idx=\"1\"]";
$('div.scroll-container.mstrmojo-scrollNode').find(n).each(function(){
        $(this).trigger('click');   
            });
  • 3
    Don't use a while loop, you can use setTimeout to delay – user184994 Jun 08 '18 at 18:50
  • What does clicking on the item do? If it submits a form, that reloads the page and your script stops. – Barmar Jun 08 '18 at 18:52
  • I think @Barmar is right. the elements on the dossier are reloaded, but not the page and "uncaught Error:invalid state" errors are produced. Can I attach a variable to the window and have the code re-execute iterativly using that? – user6206130 Jun 08 '18 at 19:11
  • You can put something into localStorage, and when the page reloads it can check for this and do something appropriate. – Barmar Jun 08 '18 at 19:12
  • Or the server script can send new Javascript in the page that it returns. – Barmar Jun 08 '18 at 19:13

1 Answers1

0

JavaScript will not wait for the 5 seconds in your code before going for the next part. You have to place the second click inside a setTimeout:

setTimeout(function(){ 
    //Click second element in the list
    var n = "div.item[idx=\"1\"]";
    $('div.scroll-container.mstrmojo-scrollNode').find(n).each(function(){
        $(this).trigger('click');
    });
}, 5000);
user184994
  • 17,791
  • 1
  • 46
  • 52
Andrez
  • 1
  • Thank. I'll give this a go. – user6206130 Jun 08 '18 at 19:01
  • But if you place code below that setTimeout, it will run before the 5s runs out. You can check this out for a better explantion: [JS Sync & Async](https://medium.com/@siddharthac6/javascript-execution-of-synchronous-and-asynchronous-codes-40f3a199e687) – Andrez Jun 08 '18 at 19:09