I have this simple script that applies a chat widget to the website. How can I delay this script from running for about 4 seconds?
I tried looking up different solutions but nothing seemed to be the same circumstances.
https://developer.mozilla.org/en-US/docs/Web/API/setTimeout
Wrap the entire script inside a named function block and call that from a setTimeout function:
(run the snippet and wait 4 seconds to see console message)
setTimeout(scriptCode, 4000);
function scriptCode (){
// place all script code here;
console.log("done");
} // end script
If you must reference the script from a named url, you can assemble a script tag in js and append it to the page after four seconds. Like this:
setTimeout(scriptCode, 4000);
function scriptCode (){
const scriptElement=document.document.createElement('script');
scriptElement.setAttribute("src", "http://scriptAddress.com");
scriptElement.setAttribute("async", "");
document.body.appendChild(scriptElement);
} // end script
The script tag will be added to the DOM after 4 seconds and will load and execute as normal