0
(function(){
    function returnResult(result){
       return result
    };
    setTimeout(function(){
        var result = window.document.querySelector('.element span').textContent.match(/\d+/)[0];
        returnResult(result)
    },500); 
})()

I'm trying to wait a set amount of time to pull data from an element on a page for web tracking purposes. The element takes a few milliseconds to load and loads dependably, so I don't need to try and do the whole mutation observer wait for the element to appear thing.

I'm just trying to figure out how to get a value out of setTimeout. I read over a similar question on here and it seems you have to do whatever you wanted to do with the data from within setTimeout and you cannot return data out of setTimeout.

Is there another way to make setTimeout synchronous so that it is blocking of the code that follows it so something like the below would work?

(function(){
     setTimeout(function(){},500); 
     return window.document.querySelector('.element span').textContent.match(/\d+/)[0]; 
 })()
Yale Newman
  • 1,141
  • 1
  • 13
  • 22
  • 2
    Just use a promise, and wait till that promise resolves with the value you want to return. You could use async/await to write this in a more "sync" style (though it would still just be promises) – Andrew Li Jul 12 '19 at 20:46
  • Either use the promise that @Li357 mentioned, or create a function that does with the data whatever you need. Then instead of returning from the `setTimeout` you can simply call the function and pass the info as parameters – adr5240 Jul 12 '19 at 20:47
  • `setTimeout(function(){ yourFunction({info needed}) },500); but I would do the `querySelector` within this `yourFunction` instead of the timeout – adr5240 Jul 12 '19 at 20:50
  • the issue is that i need support across as many browsers and their versions as possible, so doesn't that count out ES6 modifications that allow for promises? Also, returning the value is what I want to do. I'm not looking to do anything else with it. – Yale Newman Jul 12 '19 at 22:06

0 Answers0