简体   繁体   中英

Get a returned value from a simple setInterval function

Why is it that if I have a function that returns a value it shows in the console each time I call the function but if I place the same function in setInterval it quits returning the value. IE:

function run() {
    return 'Hello world';
}

a = setInterval(run, 1000); //'Hello world' is not shown in the console every second

//Calling run() returns 'Hello world' to the console
run(); //'Hello world'

instead of return Hello World, you should console.log("Hello World") if that is the effect you want. Your script is being interpreted as you expect. It is running a function that returns "Hello World" every second. But that returned string is not being logged to the console until you include that piece of functionality.

function run() {
  console.log("Hello world");
  return 'Hello world';
}

The purpose of setInterval is to execute a function every X milliseconds. In your original code, when the run function returns each time, its returning to the context of the native setInterval function. The setInterval function does NOT console.log it out for you automatically.

When you run your code run(); , it returns the value Hello world . The only reason you see its value displayed on screen is because the console evaluates the expression and returns its value for you to see.

Your target is not console as output stream in your code but when you invoke the run() from console it simply returns the string to console, may try callback:

var run = function(fn){
    fn("hello world");//invoke the callback function
};

setTimeout(function(){
  run(alert);//target output to alert
  run(console.log);//now its console
}, 500);

Liam is correct. This is what is a bit confusing:

Calling run() returns 'Hello world' to the console is not what is happening. Calling run() returns "Hello world" to the caller of the function .

If you are in the console, and enter an expression, the value of the expression is output to the console. If you enter 1+1 you will get 2 . If you enter Math.sqrt(25) you will get 5 . So if you enter run() you will get Hello world .

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