Tampermonkey js/jquery/ajax how to add a sleep?

5.9k Views Asked by At

For a page like https://www.converto.io/?v=EbuYMynCWV8, I have a Tampermonkey script to automatically:

  1. Choose mp4 format
  2. Click CONVERT button.

It works, but sometimes maybe it's too fast and finally I get mp3 format download links.
So now I want to put in a sleep time between the two steps. Test result is the code only finishes first step. Any idea?

My code:

// ==UserScript==
// @name     _ConverTo, Automatically select mp4
// @match    https://www.converto.io/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
//- The @grant directive is needed to restore the proper sandbox.

waitForKeyElements (".format-select:has(option[value=mp4])", selectFinickyDropdown);  //------ step 1,choose mp4 format------

function selectFinickyDropdown (jNode) {
    var evt = new Event ("click");
    jNode[0].dispatchEvent (evt);

    jNode.val('mp4');

    evt = new Event ("change");
    jNode[0].dispatchEvent (evt);

    setTimeout("secondStep()", 10000);    //--- sleep 10s then step 2,click CONVERT button -------
}

function secondStep() {
    waitForKeyElements (".convert-btn", clickbuttonconvert);
}

function clickbuttonconvert (jNode) {
    var evt = new Event ("click");
    jNode[0].dispatchEvent (evt);
}
1

There are 1 best solutions below

3
On BEST ANSWER

Remove the quotes and parens from the setTimeout call, the first parameter is supposed to be the function itself.

setTimeout(secondStep, 10000);

See the setTimeout reference at MDN.