简体   繁体   中英

Passing/Accessing values from separate thread in javascript

I am trying to use following code which I had found/edited in another post. I would like to use the function "IsValidImageUrl()" to instantly return result on the fly. Since this function runs in a separate thread, I had a trouble getting the value, for example, if I had "return True;" in place of "isValid=true;" I always get "undefined" in return. So I tried to use global variable "isValid", but it always seem to be one step behind, meaning I need to call the function twice, to get the result for the first call.

What am I fundamentally missing? or would you be able to suggest another method that I can do it?

Thank you!

<script>
    var isValid;
    function IsValidImageUrl(url) {
        $("<img>", {
                      src: url,
                      error: function() { isValid=false; },
                      load: function() { isValid=true; }
                    });
     }

    IsValidImageUrl("https://www.google.com/logos/2012/hertz-2011-hp.gif");
    alert(isValid);
    IsValidImageUrl("http://google.com");
    alert(isValid);
</script>

The problem is you have to wait for the image to either load or fail before you can use the status. The best way is to give the IsValidImgUrl function a callback function (or seperate ones for success and failure) to run when the image has loaded or an error has occured.
In this example the image element is also passed to the callback functions, so that they know which image they were called for.

 function IsValidImageUrl(url, okFunc, errFunc) { var image = document.createElement("IMG"); image.src = url; image.onload = function() {okFunc(image)}; image.onerror = function() {errFunc(image)}; } function imageLoadSucces(image) { alert("image loaded: " + image.src); } function imageLoadFail(image) { alert("image load error: " + image.src); } IsValidImageUrl("https://www.google.com/logos/2012/hertz-2011-hp.gif", imageLoadSucces, imageLoadFail); IsValidImageUrl("http://google.com", imageLoadSucces, imageLoadFail); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM