這是一個問題:只能在setTimeout回調中運行JavaScript函數嗎?
定義一個名爲print
的函數,它只是輸出它獲取的參數。
但是,如果它被正常調用,它不會打印出任何東西。
只有在setTimeout回調中才會生效。
e.g:
setTimeout(function() {
print('123'); //===> 123
});
print('456'); //===> nothing output
我有一個解決方案,但我不認爲這是一個很好的方式,我改寫的setTimeout。
我想要一個更好的解決方案好奇。
var print = function() {
'use strict';
var __origSetTimeout = window.setTimeout;
window.setTimeout = function(fn, delay) {
var _fn = new Function(`(${fn.toString().replace(/print\(/g, 'print.call(this,')}).call(this);`);
return __origSetTimeout.call(window, _fn.bind({
isFromSetTimeout: true
}), delay);
};
return function print(word) {
if (!this || !!this && !this.isFromSetTimeout) return;
console.log(word);
};
}.call(null);
不可能的。你要麼定義一個上下文,要麼傳遞不同的參數,這樣函數就知道它是應該還是不應該輸出。 – Utkanos
不,也許你正在尋找別的東西,你爲什麼要這個功能? – Jerodev
保存超時的ID並使用它。 – Jivings